2016-05-06 8 views
0

これは返されたthisFunction.weather.day()が未定義です。なぜですか?私はこれを正しくしていますか?新しいオブジェクトで別のプロトタイプを呼び出す

'use scrict'; 

    var thisFunction = function(){this.event(); }; 

    thisFunction.prototype.weather = function(){ 

     this.day = "Cloudy"; 

    }; 

    thisFunction.prototype.event = function(){ 

     console.log(thisFunction.weather().day); 

    }; 

    var g = new thisFunction(); 

イベント内部の天気機能を呼び出そうとしています。あなたが下に見ることができるように、new thisFunction()に等しい新しいvar gがあります。私がイベント内の天気関数を呼び出すと、thisFunction.prototype.weather()。dayは未定義です。どうして?

答えて

1

thisFunctionは、あなたのコンストラクタ関数です。

.weather()メソッドはありません。したがって、thisFunction.weatherundefinedであり、thisFunction.weather()はエラーです。

.weather()のメソッドは、コンストラクタ自体ではなく、thisFunctionのインスタンスを意味するプロトタイプにあります。だから、あなたのコードでは、あなたができる:.event()方法の内、

g.weather() 

をそれとも、あなたがこれを行うことができます:

thisFunction.prototype.event = function(){ 

    console.log(this.weather()); 
}; 

this.weather().day作業を行うには、からreturn thisする必要があると思います.weather()方法。

thisFunction.prototype.weather = function(){ 

    this.day = "Cloudy"; 
    return this; 

}; 

thisFunction.prototype.event = function(){ 

    console.log(this.weather().day); 

}; 
+0

[OK]を私はどのように試作品の外にweather.dayを得ることができますか?プロトタイプの外に私は含まれていたvar thisf = new thisFunction(); – NodeBeginner

+0

@NodeBeginner - あなたの質問ではあなたの例で 'g.day'を使用するだけです。 – jfriend00

+0

@ NodeBeginner - これはあなたの質問にあります: 'var g = new thisFunction();' – jfriend00

関連する問題