首页 > 解决方案 > 如何将此传递给Javascript中的嵌套函数?

问题描述

我试图执行这样的事情:

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

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

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

标签: javascriptoopobject

解决方案


您可以使用箭头函数而不是常规函数来保留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();


推荐阅读