var obj = function() { /* Private variables */ var v1 = 0; var v2 = 0; /* Public variables */ this.state = false; /* Public functions */ this.update = function() { if(this.state) do_stuff(); console.log(this.state); // undefined!!! } };
So, when when I called the update function in another context with another this object, the this keyword referenced to the caller object, not to the object where it was. The result of this is that the state variable is undefined, because the caller object didn't have a state variable. I knew that the this keyword is the problem and I also knew that I need to reference to the object in its own functions. So the solution is to create a private variable and store a reference to the object in it.
var obj = function() { /* Reference to self */ var _self = this; /* Private variables */ var v1 = 0; var v2 = 0; /* Public variables */ _self.state = false; /* Public functions */ _self.update = function() { if(_self.state) do_stuff(); console.log(_self.state); // false this.somethingElse = true; } };
With this solution, if you create an object with the new keyword, the constructor is called and the _self variable will store a reference to itself. This won't mess up the this reference in other contexts.
No comments:
Post a Comment