Javascript 面向对象编程(三)

理解什么是继承

方法和属性从一个类传递到另外一个类的过程app

为何须要继承机制

funtion Person(firstName, lastName) {
    this.firstName = firstName
    this.lastName = lastName
  }
  Person.prototype.sayHi = function() {
    return "Hi" + this.firstName + " " + this.lastName;
  }

  function Student(firstName, lastName){
    return Person.apply(this, arguments);
}

Student.prototype.sayHi = function(){
    return "Hi " + this.firstName + " " + this.lastName;
}
复制代码

咱们真的须要在学生身上从新定义sayHi吗?这彷佛重复…… 那怎么办?函数

function Person(firstName, lastName){
    this.firstName = firstName;
    this.lastName = lastName;
}

Person.prototype.sayHi = function(){
    return "Hi " + this.firstName + " " + this.lastName;
}
复制代码

将一个对象的原型属性指定为另外一个对象的原型属性!优化

function Student(firstName, lastName){
    return Person.apply(this, arguments);
}

Student.prototype = Person.prototype;

var s1 = new Student('李','哈')
s1.sayHi() // "Hi 李 哈"
复制代码

有用:)!ui

继续看看 在Student prototype对象上添加一些别的this

Student.prototype.status = function(){
    return 'I am currently a student'
  }
复制代码

让咱们用Person建立一个对象spa

var p1 = new Person('下','啦')
  p1.status() // 'I am currently a student'
复制代码

哦哦……为何Person原型有student原型的属性?学生继承的是人,而不是人。prototype

问题code

  • 咱们不能将一个对象分配给另外一个对象——它只会建立一个引用!
  • 若是咱们改变Student.prototype,会影响Person.prototype
  • 咱们仍然须要来自父类原型的全部方法和属性,可是咱们想要两个彻底独立的对象——而不是引用!

一个更好的选择Object.create对象

建立一个全新的函数并接受它的第一个参数,即新建立对象的原型对象。继承

function Student(firstName, lastName){
    return Person.apply(this, arguments);
}

Student.prototype = Object.create(Person.prototype);
Student.prototype.status = function(){
    return "I am currently a student!"
}
var p1 = new Person('李', '哈');
p1.status; // undefined 
复制代码

Student.prototype 不会影响 Person.prototype !

思考为何不是new?

function Student(firstName, lastName){
    return Person.apply(this, arguments);
}

Student.prototype = new Person();
// 1. Person被执行了两次
// 2. 代码重复,增长了多余的不须要的属性在Student的原型对象上面
复制代码

优化一下

function Student(firstName, lastName){
    return Person.apply(this, arguments);
}

Student.prototype.sayHi = function(){
    return "Hello " + this.firstName + " " + this.lastName;
}

Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor; // Person
Student.prototype.constructor = Student;
复制代码

继承的两个要点

  • 将原型设置为使用另外一个原型建立的对象
  • 重置构造函数属性

总结

  • 每次使用new关键字时,在建立的对象和构造函数的prototype属性之间创建一个连接——能够使用__proto__访问这个连接
  • prototype对象包含一个名为构造函数的属性,该属性指向构造函数
  • 为了共享由构造函数建立的对象的属性和方法,将它们放在原型中,由于它是最有效的。
  • 要将方法和属性从一个原型对象传递到另外一个原型对象,咱们能够使用继承,其中包括使用对象将prototype属性设置为新建立的对象。建立并从新设置构造函数属性
相关文章
相关标签/搜索