Behrang Saeedzadeh
Behrang Saeedzadeh

Reputation: 47913

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

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.

Upvotes: 2

Views: 1014

Answers (3)

Daniel Earwicker
Daniel Earwicker

Reputation: 116654

The method you've used is often called the "that reference", because the name that is commonly used as a name for the copy of the this reference. See Crockford's talks on JavaScript for example.

Upvotes: 1

Gabor de Mooij
Gabor de Mooij

Reputation: 3007

You can pass a reference to this to the function, but your solution seems fine to me. You are just using the lexical scoping rules of Javascript so what is wrong?

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074148

Your solution is perfectly fine. Since you already have a closure there, may as well make use of it, that's absolutely fine.

But if you like, you can use jQuery.proxy instead, like this:

MyClass.prototype.myMethod2 = function() {

    $.jQuery({success: jQuery.proxy(function(data) {
        this.myMethod2();
    }, this), ...});
}

Again, though, there's nothing wrong with your original solution. Using proxy can be helpful, though, when you want to reuse a function in lots of different places, or when you don't already have a closure and don't want to introduce one (perhaps because it would close over a lot of unrelated stuff). The good thing about proxy is that it creates a closure over a controlled set of stuff and not over the current scope.

Upvotes: 1

Related Questions