prototype是构造函数的特殊属性,而不是实例的。
当您使用 调用构造函数时new Func(),引擎将创建一个新对象,该对象继承自Func.prototype并this在构造函数内部设置以引用新对象。
因此,除了this.prototype作为普通属性之外,在分配发生时继承已经发生。
由于您没有为 分配任何方法MyClass.prototype,因此您不必在此处对原型继承做任何事情。您所要做的就是使用[MDN]MyClass应用到新创建的实例:.call
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 中都会变得更容易。