本文共 1609 字,大约阅读时间需要 5 分钟。
function Parent (name) { this.name = name; this.colors = ['red', 'blue', 'green'];}Parent.prototype.getName = function () { console.log(this.name)}function Child (name, age) { Parent.call(this, name); this.age = age;}Child.prototype = new Parent();var child1 = new Child('kevin', '18');
console.log(child1)复制代码组合继承最大的缺点是会调用两次父构造函数。
一次是设置子类型实例的原型的时候:Child.prototype = new Parent();
一次在创建子类型实例的时候:
var child1 = new Child('kevin', '18');
回想下 new 的模拟实现,其实在这句中,我们会执行:
Parent.call(this, name);
在这里,我们又会调用了一次 Parent 构造函数。
所以,在这个例子中,如果我们打印 child1 对象,我们会发现 Child.prototype 和 child1 都有一个属性为colors,属性值为[‘red’, ‘blue’, ‘green’]。function Parent (name) { this.name = name; this.colors = ['red', 'blue', 'green'];}Parent.prototype.getName = function () { console.log(this.name)}function Child (name, age) { Parent.call(this, name); this.age = age;}function object(o) { function F() {} F.prototype = o; return new F(); // 通过构造一个介于 Parent 与 Child 之间的对象,并使该对象的 prototype 属性指向 Parent 的 prototype对象, // 来避开通过调用 Parent 构造函数的方式来产生一个 prototype 指向Parent prototype对象的对象。}function prototype(child, parent) {// 不直接child.prototype=parent.prototype呢?// 原因 : 当我们想给 Child 的prototype里面添加共享属性或者方法时,如果其 prototype 指向的是 Parent 的 prototype,那么在 Child 的 prototype 里添加的属性和方法也会反映在 Parent 的 prototype 里面,// 这明显是不合理的,这样做的后果是当我们只想使用 Parent 时,也能看见 Child 往里面扔的方法和属性。// 所以需要每个构造函数都需要持有自己专用的prototype对象 var prototype = object(parent.prototype); prototype.constructor = child; child.prototype = prototype;}prototype(Child, Parent);var child1 = new Child('kevin', '18');console.log(child1);
转载地址:http://uxvxi.baihongyu.com/