问题描述
var ball = {
x: 20,
y: 500,
vx: 100,
vy: 100,
width: 13,
height: 13,
draw: function() {
var img = new Image();
img.src = 'images/ball.png';
img.onload = function(){
ctx.drawImage(img, this.x, this.y);
};
},
我希望 drawImage() 代码行引用 ball.x 和 ball.y.我想使用this"关键字,而不是使用 ball.x 和 ball.y,这样我就可以将球对象转换为一个函数,如果我最终想要(能够制作 ball1、ball2)、ball3 等).我认为this"不再是指球,因为它在嵌套函数中?如果不将 ball.x 和 ball.y 硬编码到 drawImage 参数中,有没有办法解决这个问题?
I want the drawImage() line of code to refer to the ball.x and ball.y. Instead of using ball.x and ball.y, I want to use "this" keyword so that i can turn the ball object into a function that is a mass constructor/prototype if i end up wanting to (able to make ball1, ball2, ball3 etc.). I think "this" is not referring to ball anymore because it's in a nested function? Is there any way around that without hard-coding ball.x and ball.y into the drawImage arguments?
推荐答案
这是 JavaScript 的棘手之处之一:this
是动态的.简而言之,解决方案是将您想要的 this
放在一个变量中,同时使用该变量来引用它:
This is one of the tricky things about JavaScript: this
is dynamic. To put it simply, the solution is to put the this
you want in a variable while you have it and use that variable to refer to it:
var ball = {
// ...
draw: function() {
// ...
var myself = this;
image.onload = function() {
// use myself rather than this
};
}
};
另一个解决方案是修复this
的值.这是使用 bind
:
Another solution is to fix the value of this
. That is done using bind
:
var ball = {
// ...
draw: function() {
// ...
image.onload = function() {
// ...
}.bind(this);
}
};
这会将 onload
函数内的 this
的值绑定到调用 draw
时的任何值.后一种解决方案不适用于较旧的浏览器,但很容易被修补.
That will bind the value of this
inside the onload
function to whatever it was when draw
was called. This latter solution won't work on older browsers, but it is easily shimmed.
这篇关于javascript“这个"关键字不是指正确的东西的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!