1.创建两个构造函数
这里我们创建了Person和Student两个构造函数
function Person() {
this.friends = ["狗","猫"]
}
function Student(name) {
this.type="学生";
this.name = name;
}
var stu = new Student("张三");
console.log(stu.type); // 学生
console.log(stu.name); // 张三
console.log(stu.friends); // undefined
图如下所示:
从上图中可知构造函数Student与构造函数Person并没有直接的联系,因此构造函数Student的实例stu并不能获取到属性friends。
2.关联两个构造函数
在此之前的prototype随记中说过,构造函数的原型对象也是一个对象,而构造函数的实例也是一个对象,那么我们能不能把构造函数的原型对象作为另一个构造函数的实例呢?接下来我们把代码改造一下。
function Person() {
this.friends = ["狗","猫"]
}
function Student(name) {
this.type="学生";
this.name = name;
}
var p = new Person(); // 此行为新增的代码
Student.prototype = p; // 此行为新增的代码
Student.prototype.constructor = Student;
// Student.prototype = new Person(); 上述两行代码可简化为这一行
var stu = new Student("张三");
console.log(stu.type); // 学生
console.log(stu.name); // 张三
console.log(stu.friends); // ["狗","猫"]
上述新增代码中,首先创建Person实例p,把Student的prototype指向实例p(此处需要注意的是并不是将Person的原型对象指向实例p),后续创建实例stu时,stu的__proto__也指向了实例p,因此在查找friends属性时,会沿着原型链在p中找到该属性。因为在改变Student的prototype的同时,Student.prototype.constructor的值原本为Student的也被覆盖为空了,因此最好手动添加上去。图如下所示:
3.原型链继承存在的问题
问题1:继承过来的实例属性,如果是引用类型,会被多个子类实例共享
function Person() {
this.friends = ["狗","猫"]
}
function Student(name) {
this.type="学生";
this.name = name;
}
Student.prototype = new Person();
Student.constructor = Student; // 添加constructor
var stu1 = new Student("张三");
var stu2 = new Student("李四");
console.log(stu1.friends); // ["狗","猫"]
console.log(stu2.friends); // ["狗","猫"]
/* 修改stu1中的friends,会导致stu2中的friends也改变 */
stu1.friends[0]="老鼠";
console.log(stu2.friends); // ["老鼠","猫"]
问题2:无法传递参数到父构造函数中,只能继承父函数中的写死的值
此问题将在下一章"组合继承"中得到解决。
本人前端小白一枚,对原型链继承的问题也不能说精通,只能把自己理解到的部分写成博客供新人参考学习。有问题请各位指出,本人会做改进,谢谢~