I have the following which is a simplified version of what I have:
function MyClass(a,b) {
this.a = a;
this.b = b;
}
MyClass.prototype.f1 = function(a) {
this.a = a;
};
MyClass.prototype.f2 = function(a) {
this.f1(a);
};
var mc1 = new MyClass(1,2);
Now I am getting an error saying:
this.f1 is undefined
If I move f1 out to its own function, there error is gone.
What could be causing this problem?
I know if you run the simplified version above it should work, but what could be causing the issue in my codebase? (I can’t post it here, but any hints on what to look for?)
Update
Ok after tracing it in firebug, it seems the keyword ‘this’ has been rebound somehow and it is no longer bound to the class MyClass, hovering over it is shows ‘function’.
What happened is that I set this function MyClass.f2 as a callback to Telerik editor, and it has somehow changed the scope of ‘this’.
What are my options to fix this?
One option is to refactor your code to a version that avoids using the
prototypeproperty:This way you have a persistent reference to the current instance that you can use instead of the
thiskeyword.