参考“这个”在javascript中的父闭包 [英] Referring to "this" in a parent closure in javascript
问题描述
我想在Javascript中执行此操作:
I want to do this in Javascript:
function Z( f )
{
f();
}
function A()
{
this.b = function()
{
Z( function () { this.c() } );
}
this.c = function()
{
alert('hello world!');
}
}
var foo = new A();
foo.b();
可以这样做:
function Z( f )
{
f();
}
function A()
{
var self = this;
this.b = function()
{
Z( function () { self.c() } );
}
this.c = function()
{
alert('hello world!');
}
}
var foo = new A();
foo.b();
推荐答案
< >解决方案
保持引用父(像你有)是一个好的方法,但是对于你的具体示例,没有必要使用匿名包装器,你可以直接传递函数,像这样: / p>
Keeping a reference to the parent (like you have) is a good approach, however for your specific example there's no need for the anonymous wrapper, you can pass the function directly, like this:
var self = this;
this.b = function()
{
Z(self.c);
}
你可以在这里测试它,没有这个包装器实际上不需要 self
变量,你可以使用 this
,如下所示:
You can test it out here, and without this wrapper there's actually no need for the self
variable, you can just use this
directly, like this:
this.b = function()
{
Z(this.c);
}
在下面的注释中有一些混淆,上面的代码为问题维护 this
,如果你想保留这个
/ context在回调中,使用 .call()
喜欢这个:
Since there seems to be some confusion in the comments below, the above code maintains this
for the question, if you want to maintain the this
/context inside the callback as well, use .call()
like this:
this.b = function()
{
Z.call(this, this.c);
}
并且 Z
:
function Z( f )
{
f.call(this);
}
这篇关于参考“这个”在javascript中的父闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!