Confused why this javascript is causing me issues. Defined a class and prototype methods
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 func开发者_开发百科tion 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 prototype
property:
function MyClass(a, b) {
var t = this;
t.f1 = function(a) {
t.a = a;
};
t.f2 = function(a) {
t.f1(a);
};
// constructor code...
t.a = a;
t.b = b;
}
This way you have a persistent reference to the current instance that you can use instead of the this
keyword.
As you mention everything looks fine. There are a couple of possibilities
1) You defined a 'subclass' of MyClass
and didn't hook up the prototype/constructors correctly.
2) You might have changed the definition of the MyClass
object (i.e. class) at runtime, so it wouldn't work after a certain point (yay dynamic languages)
3) You trying to invoke f1
from something that is not a MyClass
instance.
without seeing the invocation that is causing the issue, and the surrounding code, I can't say more.
精彩评论