gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 15:01:00 24 4
gpt4 key购买 nike

我写了一个对象构造函数,有两个方法,其中一个通过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();

关于javascript - js中其他方法调用setInterval方法无法访问对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35431437/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com