2017-08-10 6 views
1

私の親クラスは、私の子供はコール親プロトタイプ

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を持っている

function Parent() {} 

    Parent.prototype.get = function() {} 

    Parent.prototype.start= function() { this._start() } 

です。親プロトタイプ関数をどのように呼び出すことができますか?ありがとう。

+0

'はconsole.log(これは)' ES6クラスを使用することを検討して – Laazo

+1

何 'this'リファレンスを参照していることだろう場合と'super'メソッドです。 – 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();

1を変更することで、あなたは同様に他を変えることと思いますので、親と子が今、同じプロトタイプを持っていることに注意してください。
Object.createを使用して、あなたがそれを避けるために持っているいくつかの理由で(または割り当てる)

Child.prototype = Object.create(Parent.prototype); 
関連する問題