![](/img/trans.png)
[英]Assigning prototype methods *inside* the constructor function - why not?
[英]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()的方法
我假设在SecondClass的构造函数中执行this.prototype = new MyClass()会导致它从MyClass的inhert方法?
我确信有更好的方法可以做到这一点,但我试图理解prototype关键字的行为。
prototype
是构造函数的特殊属性,而不是实例的特性 。
当您使用new Func()
调用构造函数时,引擎将创建一个从Func.prototype
继承的新对象,然后在构造函数内部设置this
以引用新对象。
因此,除了this.prototype
只是一个普通的属性,继承已经发生在赋值发生时。
由于您没有为MyClass.prototype
分配任何方法,因此您不必在此处对原型继承执行任何操作。 您所要做的就是使用.call
[MDN]将MyClass
应用于新创建的实例:
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中都会变得更容易 。
名为“prototype”的属性仅对作为函数的对象感兴趣。 为构造函数中的“prototype”属性赋值不起作用(在本例中); 重要的是构造函数本身的“原型”属性。
SecondClass.prototype = new MyClass();
或者其他的东西。 构造函数的原型对象在构造的所有实例之间共享,因此通过构造函数参数改变原型也没有多大意义。
你可以做的另一件事是从“SecondClass”中调用“MyClass”构造函数:
function SecondClass(b) {
MyClass.call(this, b);
this.getB = function() {
return 6;
};
}
这将具有使效果this
是在构建new SecondClass()
调用的“MyClass的”构造进行装饰。 它不会真的是继承,但你会得到一个“getA”函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.