我正在尝试使用它。在创建对象的函数内部。但这似乎不起作用。
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,因此我需要渲染图像。有任何想法吗?
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 Harmony),则可以使用另一种解决方案,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";
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句