es5继承,子类必须指定构造器constructor为自己的构造函数

常用的原型继承

1:Children.prototype = new Father()

2:Children.prototype = Object.Create(Father.prototype)

 

矛盾点:以上两种继承,子类的构造器会指向父类,这在某种场景下会引发一定问题

console.log(Children.constructor) // function Father(){}

 

场景:在闭包①中实现继承

 1     //父类
 2     function Father() {}
 3     console.log(Father.prototype); //{constructor: ƒ}
 4     //此时想在闭包里面创建一个子类
 5     var child;
 6     (function () {
 7       function Children() {}
 8       Children.prototype = Object.create(Father.prototype)
 9       //如果不在此指定子类的构造器的指向
10       //Children.prototype.constructor = Children
11       child = new Children();
12     })()
13     //子类的构造器默认指向父类
14     console.log(child.constructor); //Father() {}
15     //此时在子类上添加原型属性
16     child.constructor.prototype.age = 15
17     //子类上添加原型属性,会直接添加到父类上
18     console.log(Father.prototype); //{age: 15, constructor: ƒ}

结论:子类不指定构造器,当使用constructor在构造函数的prototype上新增属性,会直接添加到父类上

注:①:本文在闭包中实现的继承,是因为在闭包中创建的子类,在外部不能直接在 构造函数的prototype 上新增属性,这样只能通过 实例对象的constructor.prototype 添加新属性

 

posted @ 2020-05-26 08:17  qq329988300  阅读(411)  评论(0)    收藏  举报