我有一個簡單的JS對象,模擬交通燈:JavaScript的setTimeout的不工作
function TrafficLight(redTime, yellowTime, greenTime) {
var self = this;
this.__timer = null;
this.__state = null;
this.__redTime = redTime;
this.__yellowTime = yellowTime;
this.__greenTime = greenTime;
var setnewtimer = function (delay, func) {
console.log('SET!');
if (self.__timer) {
clearTimeout(this.__timer);
}
self.__timer = setTimeout(delay, func);
};
TrafficLight.prototype.toRed = function() {
this.__state = 'red';
setnewtimer(this.__redTime, function() {
console.log('RED!');
self.toGreen();
});
};
TrafficLight.prototype.toGreen = function() {
this.__state = 'green';
setnewtimer(this.__greenTime, function() {
console.log('GREEN');
self.toYellow();
});
};
TrafficLight.prototype.toYellow = function() {
this.__state = 'yellow';
setnewtimer(this.__yellowTime, function() {
console.log('YELLOW');
self.toRed();
});
};
TrafficLight.prototype.state = function() {
return this.__state;
};
this.toGreen();
}
但是當我做一個TrafficLight
對象(如var a = new TrafficLight(1000, 1000, 1000);
),每a.state()
調用返回(使交通燈沒有按」牛逼通過定時器改變它的狀態。這有什麼錯我的代碼?
* 「JavaScript的setTimeout的不起作用」 *是這樣,你知道的。但它不是JavaScript,它是瀏覽器的。 – 2014-09-29 09:13:57