如何访问闭包父对象的方法?
我定义了一个名为 MyClass
的类,并为其定义了两个方法 myMethod1
和 myMethod2
:
function MyClass() {}
MyClass.prototype.myMethod1 = function() {...};
MyClass.prototype.myMethod2 = function() {...};
在 myMethod1
内部,我使用 jQuery,并且那里定义了一个回调闭包:
MyClass.prototype.myMethod2 = function() {
$.jQuery({success: function(data) {
this.myMethod2();
}, ...});
}
现在的问题是 this
不再引用 MyClass
。问题是我该如何参考呢?目前,我已将其分配给名为 thisObj
的变量,并以这种方式访问它:
MyClass.prototype.myMethod2 = function() {
var thisObj = this;
$.jQuery({success: function(data) {
thisObj.myMethod2();
}, ...});
}
是否有更好的方法从嵌套在 中的闭包访问
MyClass.this
myMethod2?
提前致谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您使用的方法通常称为“that 引用”,因为名称
that
通常用作this
引用的副本的名称。例如,请参阅 Crockford 关于 JavaScript 的演讲。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 thethis
reference. See Crockford's talks on JavaScript for example.你的解决方案非常好。既然你已经有一个闭包,不妨使用它,那绝对没问题。
但如果您愿意,可以使用
jQuery.proxy
代替,就像这样:不过,同样,您原来的解决方案没有任何问题。不过,当您想在许多不同的地方重用某个函数时,或者当您还没有闭包并且不想引入闭包时(可能是因为它会关闭很多不相关的东西)。代理的好处是它在一组受控的内容上创建一个闭包,而不是在当前作用域上。
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: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 aboutproxy
is that it creates a closure over a controlled set of stuff and not over the current scope.您可以将对此的引用传递给该函数,但您的解决方案对我来说似乎很好。您只是使用了 Javascript 的词法作用域规则,那么有什么问题吗?
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?