Javascript-форум (https://javascript.ru/forum/)
-   Элементы интерфейса (https://javascript.ru/forum/dom-window/)
-   -   вызов метода объекта в качестве аргумента setTimeout (https://javascript.ru/forum/dom-window/5327-vyzov-metoda-obekta-v-kachestve-argumenta-settimeout.html)

maxval 05.10.2009 10:07

вызов метода объекта в качестве аргумента 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();">

Kolyaj 05.10.2009 10:29

Counter.prototype.count = function() {
    var that = this;
    this.countVal--;
    setTimeout(function() {
        that.printCounter();
    }, 1000);
}

maxval 05.10.2009 10:51

спасибо !

как раз в эти минуты пришел к тому же выводу. :)

Counter.prototype.count = function() {
    this.countVal--;
    object = this;
    setTimeout(function() { object.printCounter.call(object)},1000);
}


проблема была в том, что при запуске setTimeout контекст this меняется на window

Kolyaj 05.10.2009 11:12

http://javascript.ru/var Не надо пренебрегать.


Цитата:

Сообщение от maxval
object.printCounter.call(object)

Это то же самое, что и
object.printCounter()


Часовой пояс GMT +3, время: 12:55.