【问题标题】:How to pass this to a nested function in Javascript?如何将此传递给Javascript中的嵌套函数?
【发布时间】:2020-05-16 20:34:19
【问题描述】:

我试图执行这样的事情:

class A {
  functionA() {
    setTimeout(function() {
      console.log(this);
    }, 1000)
  }
}

const a = new A();
a.functionA();

但是this 总是引用窗口对象。我知道你可以设置类似var a = this 的东西,但是有没有更优雅的方法可以将它从对象传递到内部函数?

【问题讨论】:

  • functionA() { setTimeout(console.log, 3000, this); ...正确使用setTimeout

标签: javascript oop object


【解决方案1】:

您可以使用箭头函数而不是常规函数来保留 this 上下文:

class A {
  functionA() {
    setTimeout(() => {
      console.log(this);
    }, 1000)
  }
}

const a = new A();
a.functionA();

另一种方法是.bind(this),它将创建一个有界this 上下文的函数:

class A {
  functionA() {
    setTimeout((function() {
      console.log(this);
    }).bind(this), 1000)
  }
}

const a = new A();
a.functionA();

【讨论】:

    【解决方案2】:

    为了满足 OP 提出更优雅的方式的期望,我建议在考虑任何其他方法之前正确使用 setTimeout ...

    class A {
      constructor() {
        this.delay = 3000;
      }
      functionA() {
        setTimeout(console.log, this.delay, this);
      }
    }
    
    const a = new A();
    a.functionA();
    .as-console-wrapper { max-height: 100%!important; top: 0; }

    【讨论】:

      【解决方案3】:

      除了塞巴斯蒂安的回答,还可以有另一种解决方案

      class A {
        functionA() {
          const that = this
          setTimeout(function() {
            console.log(that);
          }, 1000)
        }
      }
      
      a = new A();
      a.functionA();
      

      【讨论】:

      • ...范围或上下文?.. OP,顺便说一句,知道这个解决方案。这是要求更优雅的方式
      • 上下文,让我们切换回我们最喜欢的“那个”,以免混淆
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-26
      相关资源
      最近更新 更多