javascript在函数中使用此函数
我正试着用这个。在创建对象的函数内部。但它似乎不起作用javascript在函数中使用此函数,javascript,this,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 = function() {
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,我需要这样才能渲染图像。有什么想法吗?
此
不再指向第一个函数中的同一对象,请尝试分配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";
}
您需要这样做,因为当您在onload
方法中时,this
的值会发生变化
正如@JamesMcLaughlin在下面指出的,如果您使用ECMA6(Javascript Harmony),另一种解决方案是,如果您使用arrow函数语法,您可以为这个
保留相同的值:
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";
}
此
不再指向与第一个函数中相同的对象,请尝试分配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";
}
您需要这样做,因为当您在onload
方法中时,this
的值会发生变化
正如@JamesMcLaughlin在下面指出的,如果您使用ECMA6(Javascript Harmony),另一种解决方案是,如果您使用arrow函数语法,您可以为这个
保留相同的值:
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";
}
你应该接受另一个答案,但我会把这个贴出来,以备将来参考。如果您的目标是ES6,可以使用fat箭头:
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";
}
你应该接受另一个答案,但我会把这个贴出来,以备将来参考。如果您的目标是ES6,可以使用fat箭头:
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";
}
该函数中的
指的是图像console.log(此)
查看。谢谢,是的,我意识到了这一点,但不知道该怎么办。此函数中的
指的是图像console.log(这个)
来看看。谢谢,是的,我有点意识到这一点,但不知道该怎么办。谢谢,它成功了你可以在11分钟内接受答案。。无聊的。哈哈。@Kar-标记答案是使用的一个组成部分,所以…@Kar-hahaha,你可以随时接受它,很乐意帮助:)@leetylor我知道这一点?我在表达我对等待时间的悲伤。嗯……谢谢,它成功了你可以在11分钟内接受答案。。无聊的。哈哈。@Kar-标记答案是使用的一个组成部分,所以…@Kar-hahaha,你可以随时接受它,很乐意帮助:)@leetylor我知道这一点?我在表达我对等待时间的悲伤。smh…很好,我会注意到。是的,这是一个很好的观点,我会在我的回答中引用你的帖子,让谷歌人看到很好,我会注意到。是的,这是一个很好的观点,我会在我的回答中引用你的帖子,让谷歌人看到