我的父班是
function Parent() {}
Parent.prototype.get = function() {}
Parent.prototype.start= function() { this._start() }我的孩子
function Child(){ Parent.call(this, arguments) }
Child.prototype._start = function(){ this.get() /* error here - this.get is not a function*/ }
util.inherits(Child, Parent);当我这么做
new Child().start()我发现了一个错误this.get is not a function。如何调用父原型函数?谢谢。
发布于 2017-08-10 15:05:42
由于不鼓励使用util.inherits,所以应该对类使用extends,但您似乎只有常规的函数,这意味着在开始进一步扩展它之前,可以将子实例设置为与父类相同的原型。
function Parent() {}
Parent.prototype.get = function() {
console.log('works fine');
}
Parent.prototype.start = function() {
this._start();
}
function Child() {
Parent.call(this, arguments);
}
Child.prototype = Parent.prototype;
Child.prototype._start = function() {
this.get();
}
var instance = new Child();
instance.start();
请注意,现在父母和孩子拥有相同的原型,因此通过更改其中一个,您也可以更改另一个原型。
如果出于某种原因,您必须避免这样做,使用Object.create (或赋值)可以做到这一点。
Child.prototype = Object.create(Parent.prototype);https://stackoverflow.com/questions/45617266
复制相似问题