Javascript:如何从类的一个函数中的一个函数访问类属性 [英] Javascript: How to access a class attribute from a function within one of the class's functions
本文介绍了Javascript:如何从类的一个函数中的一个函数访问类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在类的某个特定功能内,我需要使用setInterval
来中断代码的执行.但是,在setInterval
函数中,"this"不再引用类"myObject".如何从setInterval
函数中访问变量名称"?
Within my a certain function of a class, I need to use setInterval
to break up the execution of the code. However, within the setInterval
function, "this" no longer refers to the class "myObject." How can I access the variable "name" from within the setInterval
function?
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"不同.
This should work. The anonymous function's "this" is not the same "this" as your myObject's "this."
这篇关于Javascript:如何从类的一个函数中的一个函数访问类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文