在构造函数内部分配原型 [英] Assigning prototype inside constructor
问题描述
我有此代码:
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()的方法
The output tells me that a has no method called getA()
我认为在SecondClass的构造函数中执行this.prototype = new MyClass()会使它继承MyClass的方法吗?
I assumed that doing this.prototype = new MyClass() inside the constructor for SecondClass would cause it to inhert methods from MyClass?
我敢肯定有更好的方法可以做到这一点,但是我试图理解原型关键字的行为.
I'm sure there are better ways to do this, but I am trying to understand the behaviour of the prototype keyword.
推荐答案
prototype
是构造函数的特殊属性,而不是实例.
prototype
is a special property of the constructor function, not of the instance.
当您使用 new Func()
调用构造函数时,引擎将创建一个继承自 Func.prototype
的新对象,然后设置 this
构造函数中的引用新对象.
When you call the constructor function with new Func()
, the engine will create a new object which inherits from Func.prototype
and then sets this
inside the constructor function to refer to the new object.
因此,除了 this.prototype
只是一个普通属性之外,继承在分配发生时就已经发生.
So, aside from this.prototype
just being an ordinary property, the inheritance already took place when the assignment takes place.
由于您没有为 MyClass.prototype
分配任何方法,因此您无需在此处进行原型继承的任何操作.您要做的就是使用 .call
[MDN] :
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
继承自它.完整的设置如下所示:
However, you should add all methods that are shared by instances to the prototype and then let each instance of SecondClass
inherit from it. This is how a complete setup could look like:
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中将变得更容易.
这篇关于在构造函数内部分配原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!