2015-11-25 60 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