2015-11-25 41 views
0

我正在嘗試使用這個函數。在創建對象的函數內部。但它似乎沒有工作。javascript函數中的這個函數

function enemy(x, y) { 
     this.x = x; 
     this.y = y; 
     this.width = 32; 
     this.height = 32; 
     this.img = new Image(); 
     this.ready = false; 
     this.img.onload = function() { 
      this.ready = true; 
     } 
     this.img.src = "images/barney.png"; 
    } 

this.ready從未設置爲true,我需要這樣才能渲染圖像。有任何想法嗎?

+0

該函數中的'this'是指圖像。 'console.log(this)'來看看。 – zerkms

+0

謝謝,是的,我有點意識到,但不知道該怎麼辦。 – Kar

回答

3

this不再指向同一個對象,因爲它是第一個功能,儘量分配var self = this

function enemy(x, y) { 
     this.x = x; 
     this.y = y; 
     this.width = 32; 
     this.height = 32; 
     this.img = new Image(); 
     this.ready = false; 
     var self = this; // note here how we save the value of `this` 
     this.img.onload = function() { 
      self.ready = true; // and use that saved `this` here 
     } 
     this.img.src = "images/barney.png"; 
    } 

你需要這樣做,因爲this變化值,當你的onload內方法。

由於@JamesMcLaughlin低於所指出的,另一種解決方案,如果你使用ECMA6(和諧的Javascript),你可以保持相同的值this如果您使用箭頭函數語法:

function enemy(x, y) { 
     this.x = x; 
     this.y = y; 
     this.width = 32; 
     this.height = 32; 
     this.img = new Image(); 
     this.ready = false; 
     this.img.onload =() => this.ready = true; 
     this.img.src = "images/barney.png"; 
    } 
+0

感謝它的工作! '你可以在11分鐘內接受答案'。大聲笑。 – Kar

+0

@Kar - 標記答案是使用SO的一個組成部分... –

+0

@卡哈哈哈,你可以隨時接受它,只是樂意幫助:) – Macmee

3

你應該接受另一個答案,但我會張貼這個以備將來參考。如果您的目標是ES6,則可以使用胖箭頭:

function enemy(x, y) { 
    this.x = x; 
    this.y = y; 
    this.width = 32; 
    this.height = 32; 
    this.img = new Image(); 
    this.ready = false; 
    this.img.onload =() => { 
     this.ready = true; 
    } 
    this.img.src = "images/barney.png"; 
} 
+0

不錯,我會注意到的。 – Kar

+0

這是一個奇妙的點,我會在我的回答中引用您的帖子,所以谷歌瀏覽器 – Macmee