2017-05-09 62 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() {} 
}; 

在創建函數有一個「本」。我想我明白這是做什麼的,但這個例子證明我錯了。 this關鍵字 - 在這種情況下 - 指向mainState,正確(只是一些信息:創建函數啓動一旦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中用於原型繼承的函數對象的一個​​屬性。 Javascript Prototype

-2

一兩件事,總是幫助我記得this會是什麼看出來誰是調用函數,看看這個片斷

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(); 
相關問題