I believe this one is a problem that everyone that comes from real OO languages (like Java, C++) will face when working with Javascript.
We all learn that the pointer this references the instance of the class that is being executed. Everyone did this once:
public class Foo { private String name; public String say(){ return "Hello I'm " + this.name; } }
And you expect that as a result, a String “Hello I’m {yourname}” to be printed right?
Well, this is one of the foundations of encapsulation and OO.
Now, please bear with me with this example using javascript and “OO”
function Car(x,y){ this.x = x; this.y=y; this.update = function(){ this.x = this.speed*this.time; } }
So you go and run this code:
Car c = new Car(100,100); c.update();
And it works like a charm
Then you try something like this:
var car; function init(){ car = new Car(100,100); setInterval("car.update()",20); }
And now, for some reason your code is not working, and you get undefined errors on the x,y,speed “instance” variables of your car object.
It turns out, that on Javascript, this is not actually mapping to your instance, but to the owner element that is executing your code. In the above example, it was the DOMWindow. That is a FUCKING DISASTER when you have to deal with callbacks and one of my favorite features of JS, using a function as an argument to a method.
The good news, is that there is an workaround for that. You can actually use safe contained variables inside your class by creating an instance variable that points to this
function Car(x,y){ var self = this; self.x = x; self.y=y; self.update = function(){ self.x = self.speed*self.time; } }
You’ve probably seen that before right? But (at least in my case) I had never thought about it, until I got in a two hour fight with my code about why the heck this.x was not defined.
I hope this help some folks out there having the same issue.
Cheers

