gpt4 book ai didi

Javascript:如何从类的一个函数中的函数访问类属性

转载 作者:搜寻专家 更新时间:2023-11-01 04:53:21 25 4
gpt4 key购买 nike

在我的某个类的某个函数中,我需要使用setInterval 来打断代码的执行。但是,在 setInterval 函数中,“this”不再引用类“myObject”。如何从 setInterval 函数中访问变量“name”?

function myObject() {
this.name = "the name";
}

myObject.prototype.getName = function() {
return this.name;
}

myObject.prototype.test = function() {
// this works
alert(this.name);

var intervalId = setInterval(function() {
// this does not work
alert(this.name);

clearInterval(intervalId);
},0);
}

最佳答案

myObject.prototype.test = function() {
// this works
alert(this.name);
var oThis = this;
var intervalId = setInterval(function() {
// this does not work
alert(oThis.name);

clearInterval(intervalId);
},0);
}

这应该有效。匿名函数的“this”与 myObject 的“this”不同。

关于Javascript:如何从类的一个函数中的函数访问类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/429487/

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