вызов метода объекта в качестве аргумента setTimeout
Объвляю класс следующим образом
var Counter = function(min,sec,elem){
this.elem = elem;
this.countVal = Math.round(min*60) + Math.round(sec);
}
Counter.prototype.count = function() {
this.countVal--;
//this.printCounter();
setTimeout("this.printCounter();",1000);
}
Counter.prototype.printCounter = function(){
alert(this.countVal);
}
при этом закомментированный вызов функции count() выполнялся без проблем, а вот если передать вызов аргументом в setTimeout setTimeout("this.printCounter();",1000); вызова не происходит :( соответственно в документе создание объекта осуществляю следующим образом
function startClock(){
counter = new Counter(0,15,time);
counter.count();
}
<input type="button" value="Запустить" onclick="startClock();"> |
Counter.prototype.count = function() {
var that = this;
this.countVal--;
setTimeout(function() {
that.printCounter();
}, 1000);
}
|
спасибо !
как раз в эти минуты пришел к тому же выводу. :)
Counter.prototype.count = function() {
this.countVal--;
object = this;
setTimeout(function() { object.printCounter.call(object)},1000);
}
проблема была в том, что при запуске setTimeout контекст this меняется на window |
http://javascript.ru/var Не надо пренебрегать.
Цитата:
object.printCounter() |
| Часовой пояс GMT +3, время: 17:55. |