2017-05-09 8 views
0

「this」というキーワードが次の文脈でどのように機能するかについて質問があります。 Here'sフェイザーフレームワークとコード次のようになります(私は単にあなたのためにそれを一緒に合併)とtutorial:作成機能で「this」はこのコンテキストでどのように機能していますか?

var game = new Phaser.Game(400, 490); 
game.state.add('main', mainState); 
game.state.start('main'); 

var mainState = { 
    preload: function() {}, 

    create: function() { 
    this.bird = game.add.sprite(100, 245, 'bird'); 
    }, 

    update: function() {} 
}; 

「この」があります。私はこれが何をするのか理解していると思うが、この例は私が間違っていることを証明した。 mainStateを指しています(いくつかの情報:3番目の行を開始するためにmainStateが呼び出されるとすぐに作成機能が開始されます)。

私は(mainstate.bird経由)mainState対象外の鳥にアクセスできますが、なぜそれがゲームオブジェクトの外に次のようなプロトタイプ関数を定義することが可能ではないでしょうか?

mainState.prototype.myFunction() {} 

これはエラーとなり、説明できません。

+0

おそらく、あなたは少なくとも 'mainState.prototype ...'を書く必要があるからです。私は、JavaScriptの "クラス"でプロトタイプを使うことをお勧めします。 – Guybrush

+0

@Guybrush私は 'mainState'を意味しました。それを編集しました - ありがとう。 – Faizy

+0

こちらをご覧ください:http://stackoverflow.com/questions/43246989/the-value-of-this-inside-a-function/43247403#43247403だからおそらく重複した質問です。 – Guybrush

答えて

-2

mainStateはオブジェクトリテラルです。 'prototype'は、プロトタイプの継承に使用されるjavascriptの関数オブジェクトのプロパティです。いつも私はthisがどうなるか思い出すのに役立つ Javascript Prototype

-2

ことの一つは、あなたの方法をしたい場合は、このスニペットに

var sayHi = function() { console.log(this.name) } 
 

 
var yoda = { name: "Yoda", sayHi: sayHi } 
 
var darthVader = { name: "Anakin Skywalker", sayHi: sayHi } 
 

 
// the `this` here will be the yoda object 
 
yoda.sayHi() 
 
// the `this` here will be the darthVader object 
 
darthVader.sayHi() 
 

 
window.name = "Global name" 
 
// here, since nothing was specified, the object is the global object, or the window on browsers, this the same as "window.sayHi()" 
 
sayHi()

-2

を確認し、関数を呼び出している人のために外を見ることですプロトタイプにMainStateコンストラクタ関数を作成し、プロトタイプメソッドをアタッチします。

function MainState(game) { 
    this.game = game; 
} 

MainState.prototype.create = function() { 
    this.bird = this.game.add.sprite(100, 245, 'bird'); 
}; 

MainState.prototype.myFunction = function() { }; 

// etc. 

var mainState = new MainState(game); 

mainState.myFunction(); 
関連する問題