2017-08-10 36 views
1

我的父類調用父原型

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。我怎樣才能調用父母原型功能?謝謝。

+0

'的console.log(本)'來看看'this'引用 – Laazo

+1

使用ES6類和考慮超級方法。 – zero298

回答

3

由於使用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);