如何将其传递给Javascript中的嵌套函数?

问题描述 投票:0回答:3

我正在尝试执行如下操作:

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

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

但是this始终引用窗口对象。我知道您可以设置类似var a = this的东西,但是还有一种更优雅的方法将其从对象传递到内部函数吗?

javascript oop object
3个回答
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();

0
投票

除了塞巴斯蒂安的答案,另一个解决方案可以是

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

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

0
投票

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

setTimeout
class A {
  constructor() {
    this.delay = 3000;
  }
  functionA() {
    setTimeout(console.log, this.delay, this);
  }
}

const a = new A();
a.functionA();
© www.soinside.com 2019 - 2024. All rights reserved.