Here is a (very) simplified version of my code:
function Ctor() {
this.i = 0;
this.increment = function() { this.i++; },
this.decrement = function() { this.i--; },
this.display = function() { alert(this.i); }
};
The problem is, when the code is run, under some circumstances this
now points to something else. I do more or less understand that this
changes context from one function to another, but I though my increment function (and the others) would, by the magic of closures, "remember" what this is supposed to be.
I tried just eliminating this altogether, and simply referencing i in the functions. That failed also.
What should these functions look like?
You can not rely on what's in
this
in JavaScript. More on this topic.I see you probably want to introduce private attributes like in OOP languages. John Resig described this issue very well.
JavaScript works a lot differently than conventional languages like Java, C++ or PHP. But you can get used to it :)
In the instances where
this
changes, you can do this:Example:
An alternative is to modify foo() to accept the context to execute the function with, like this: