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

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

我写了一个对象构造函数,有两个方法,一个通过setInterval(functionName, interval)调用另一个,调用的函数获取对象属性失败。

我在codepen上写了一个简单的例子: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 refers to window as it is being call in 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();