我有这个代码:
var MyClass = function(b) {
this.a = b;
this.getA = function() {
return that.a;
}
}
var SecondClass = function(b) {
this.prototype = new MyClass(b);
this.getB = function() {
return 6;
}
}
var a = new SecondClass(2);
console.log(a.getA());
输出告诉我 a 没有名为 getA() 的方法
我假设在 SecondClass 的构造函数中执行 this.prototype = new MyClass() 会导致它继承 MyClass 的方法?
我确信有更好的方法可以做到这一点,但我正在尝试理解原型关键字的行为。
prototype
是一个特殊的财产构造函数,不属于instance.
当你调用构造函数时new Func()
,引擎将创建一个继承自的新对象Func.prototype
然后设置this
在构造函数内部引用新对象。
所以,除了this.prototype
作为普通财产,继承在转让时就已经发生了。
Since you are not assigning any methods to MyClass.prototype
, you don't have to do anything with prototype inheritance here. All you have to do is apply MyClass
to the newly created instance using .call [MDN]:
var SecondClass = function(b) {
MyClass.call(this, b);
this.getB = function() {
return 6;
}
};
但是,您应该将实例共享的所有方法添加到原型中然后让每个实例SecondClass
继承它。完整的设置如下所示:
var MyClass = function(b) {
this.a = b;
}
MyClass.prototype.getA = function() {
return this.a;
};
var SecondClass = function(b) {
// call parent constructor (like 'super()' in other languages)
MyClass.call(this, b);
}
// Setup inheritance - add 'MyClass.prototype' to the prototype chain
SecondClass.prototype = Object.create(MyClass.prototype);
SecondClass.prototype.getB = function() {
return 6;
};
var a = new SecondClass(2);
console.log(a.getA());
所有这些在 ES6 中会变得更容易.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)