javascript - 在 javascript 的父闭包中引用 "this"

标签 javascript closures this

我想在 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();

有没有更好的办法?

最佳答案

保留对父级的引用(就像您拥有的那样)是一个好方法,但是对于您的特定示例,不需要匿名包装器,您可以直接传递函数,如下所示:

var self = this;
this.b = function()
{
  Z(self.c);
}

You can test it out here ,如果没有这个包装器,实际上就不需要 self变量,你可以只使用 this直接,像这样:

this.b = function()
{
  Z(this.c);
}

You can test that version here .


由于下面的评论似乎有些困惑,所以上面的代码维护this 对于这个问题,如果你想维护 this/context 在回调中也是如此,使用 .call() like this :

this.b = function()
{
  Z.call(this, this.c);
}

对于 Z :

function Z( f )
{
  f.call(this);
}

You can test it here .

关于javascript - 在 javascript 的父闭包中引用 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4019962/

相关文章:

Javascript 将样式显示从无更改为正常不起作用

swift - 在 swift 中传递函数与闭包 "weak self"作为参数

javascript - 从对象 setter 访问父 `this`

javascript - JavaScript 函数中的词法范围

c# - 什么时候使用闭包?

javascript - 您可以在其构造函数内将对象添加到数组中吗

javascript 在对象方法中传递 this

Javascript 对象继承未显示预期结果

javascript - Canvas 显示奇怪

javascript - 排除 Nest.js 中的所有/api 路由以服务 React 应用程序