我有这个代码:
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)关键字的行为。
最佳答案
prototype
是构造函数的特殊属性,而不是实例。
当你用new Func()
调用构造函数时,引擎会创建一个继承自Func.prototype
的新对象,然后设置this
在构造函数中引用新对象。
因此,除了 this.prototype
只是一个普通属性之外,在赋值发生时继承已经发生。
因为您没有为 MyClass.prototype
分配任何方法,所以您不必在此处对原型(prototype)继承做任何事情。您所要做的就是使用 .call
[MDN] 将 MyClass
应用于新创建的实例。 :
var SecondClass = function(b) {
MyClass.call(this, b);
this.getB = function() {
return 6;
}
};
但是,您应该add all methods that are shared by instances to the prototype然后让 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());
所有这些 will become easier in ES6 .
关于javascript - 在构造函数中分配原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16173901/