How to access a method of a closure's parent object?

Posted by Bytecode Ninja on Stack Overflow See other posts from Stack Overflow or by Bytecode Ninja
Published on 2010-06-14T08:27:30Z Indexed on 2010/06/14 8:32 UTC
Read the original article Hit count: 144

Filed under:
|
|

I have defined a class named MyClass and I have defined two methods myMethod1 and myMethod2 for it:

function MyClass() {}
MyClass.prototype.myMethod1 = function() {...};
MyClass.prototype.myMethod2 = function() {...};

Inside myMethod1, I use jQuery and there's a callback closure defined there:

MyClass.prototype.myMethod2 = function() {
 $.jQuery({success: function(data) {
  this.myMethod2();
 }, ...});
}

Now the problem is that this no longer is referring to MyClass. The question is how can I refer to it? At the moment I have assigned it to a variable named thisObj and access it this way:

MyClass.prototype.myMethod2 = function() {
 var thisObj = this;
 $.jQuery({success: function(data) {
  thisObj.myMethod2();
 }, ...});
}

Is there a better way to access MyClass.this from the closure nested in myMethod2?

Thanks in advance.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about closures