在我的某个类的某个函数中,我需要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); }
jacobangel.. 12
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".
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".