开发者

javascript constructor this isn't bound correctly

Problem: I define a constructor in JavaScript, I've tried almost every pattern I can think of / Google. For some rea开发者_如何学编程son no matter what I do when I call a member function of that object the this keyword is always bound to window. I don't know what to do.

JsFiddle: http://jsfiddle.net/za6SN/2/


Do

setInterval(function() {ball.draw()}, 50);

Without you will only pass the reference to the function ball.draw and this will point to window


When you pass the method reference as ball.draw, its this is set to window because it has lost its context.

The best way is to use an anonymous function. The other way is not recommended (it invokes an eval()) so I won't even mention it here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜