我有一个简单的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