1

Problem: I define a constructor in JavaScript, I've tried almost every pattern I can think of / Google. For some reason 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/

Akinos
  • 2,177
  • 1
  • 18
  • 17
  • The semantics of the `this` keyword in javascript are relatively straightforward, but not very obvious. This might help: [stackoverflow.com/questions/3127429/javascript-this-keyword](http://stackoverflow.com/questions/3127429/javascript-this-keyword) – digitalbath May 25 '11 at 23:42

2 Answers2

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

jontro
  • 9,267
  • 5
  • 37
  • 65
1

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.

Community
  • 1
  • 1
alex
  • 438,662
  • 188
  • 837
  • 957