1. 单纯性的原型链继承的缺陷:
a. 原型上任何类型的属性值,都不会被实例所重写,但是引用类型的属性值会因为实例的影响而被修改。
eg: stu1.emotion.push("愁"); //emotion属性,stu1实例本身上是没有的,是继承了父类的属性,这时对emotion属性的修改,将会对父类进行修改,从而影响到了后面实例化出来的实例。
b. 原型链不能实现子类向父类传值。
2. 借用构造函数继承: [call() apply(),解决了单纯性原型链继承,引用类型的属性值会被实例修改的问题。]
eg: function student(studentID){
this.studentID = studentID;
Person.call(this); //这样子类student继承了父类Person。
}
a. this 谁调用它,它就指向谁。
stu1调用的student函数,所以student的this指向stu1,student函数调用Person函数,所以Person的this指向student,综上,Person的this指向stu1,所以stu1有了student 和 Person上的所有属性和方法。
实质就是,实例化出来的每个实例都有构造函数和父类函数的所有属性的副本,之间互不影响。
b. 缺点: 每个实例都复制一份属性到自己身上,造成内存过大。
一旦需求变化,变化之前的实例不能很好的更新,只有之后实例化出来的实例才有新属性。
3. 最终的继承解决方案: 组合继承(在借用构造函数继承的基础上加入原型链继承,实现部分属性的公用)(把复用的属性放到父类的原型对象中)
eg: function Person(){
this.head = "脑袋瓜子";
this.emotion = ['喜','怒','哀','乐'];
}
//复用的属性,放到父类的prototype中
Person.prototype.eat = function(){
console.log('吃吃喝喝');
}
Person.prototype.sleep = function(){
console.log('睡觉');
}
function Student(studentID){
this.studentID = studentID;
Person.call(this);
}
Student.prototype = new Person(); //此处代码更改了Student实例的constructor指向,指向了Person,下面一行要改过来。
Student.prototype.constructor = Student;
var stu1 = new Student(1001);