其他方法使用 setInterval 调用的方法无法访问 js 中的对象属性

Method called by other method with setInterval can not access object property in js

本文关键字:方法 js 访问 对象 属性 setInterval 调用 其他      更新时间:2023-09-26

我用两个方法编写了一个对象构造函数,其中一个通过setInterval(functionName,interval(调用另一个,被调用的函数无法获取对象属性。

我在代码笔上写了一个简单的例子:http://codepen.io/AttilaVM/pen/ZQPVEy

function Test(value) {
    this.value = value
    this.action = function testAction() {
        console.log(this.value); // gives undefined!
    }
    this.play = function testPlay() {
        setInterval(this.action, 500);
    }
}
var test = new Test(20);
test.play();

如果在没有 setInterval 的情况下调用该方法,它将按预期工作。为什么不同?被调用的方法如何访问对象的属性?

this指的是window,因为它在setInterval(window.setInterval)

要传递当前上下文,请使用 .bind(this)bind(( 方法创建一个新函数,该函数在调用时将其 this 关键字设置为提供的值

function Test(value) {
  this.value = value
  this.action = function testAction() {
    console.log(this.value);
  }
  this.play = function testPlay() {
    setInterval(this.action.bind(this), 500);
  }
}
var test = new Test(20);
test.play();