我是一位精通C#的程序员,并且对HTML和Javascript有一点经验,但是我似乎无法弄清楚对象。
我正在尝试创建一个循环,该循环将不断更新,直到计数器达到5,然后停止循环。但在Update方法中,计数器= NaN。
这是我的确切代码。
function LoginScreen() {
this.IntervalID = null;
this.counter = 0;
this.Start = function () {
this.IntervalID = setInterval(this.Update, 60 / 1000);
};
this.Stop = function () {
clearInterval(this.IntervalID);
};
this.Update = function () {
this.counter++;
alert(this.counter);
if (this.counter > 5) this.Stop();
};
}
LS = new LoginScreen();
LS.Start();
问题是内部范围this
的你Start()
,Stop()
和Update()
功能。在这些函数中,this
指的是函数,而不是您的LoginScreen
对象。
为了解决这些问题,我喜欢使用一个小self
变量来解决范围问题。这样,无论引用self
变量是什么,都将使用该对象。这就是我的意思:
function LoginScreen() {
// add this for scope fun...
var self = this;
this.IntervalID = null;
this.counter = 0;
this.Start = function () {
self.IntervalID = setInterval(self.Update, 60 / 1000); // updated...
};
this.Stop = function () {
clearInterval(self.IntervalID); // updated...
};
this.Update = function () {
self.counter++; // updated...
alert(self.counter); // updated...
if (self.counter > 5) self.Stop(); // updated...
};
}
LS = new LoginScreen();
LS.Start();
希望这是有道理的!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句