开发者

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

开发者 https://www.devze.com 2023-01-03 14:18 出处:网络
I have defined a class named MyClass and I have defined two methods myMethod1 and myMet开发者_如何学运维hod2 for it:

I have defined a class named MyClass and I have defined two methods myMethod1 and myMet开发者_如何学运维hod2 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.


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.


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.


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消