Из того, что я собрал из других сообщений, похоже, что это невозможно, но почему я не могу назвать функцию setInterval (немного короче)?OOP стиль JS не работает с функцией setInterval
tick: function() {
var self = this;
setInterval(this.calculateTime, 1000);
}
Мне нужно использовать следующее.
tick: function() {
var self = this;
setInterval(function(){this.calculateTime()}, 1000);
}
Может ли кто-нибудь объяснить, почему это так, и успокоиться?
Пожалуйста, смотрите полный код ниже
var countdownTimer = {
init: function(end) {
this.endTime = new Date(end);
},
calculateTime: function(){
this.now = new Date();
this.difference = this.endTime - this.now;
this.seconds = Math.floor(this.difference/1000);
this.minutes = Math.floor(this.seconds/60);
this.hours = Math.floor(this.minutes/60);
this.days = Math.floor(this.hours/24);
this.hours %= 24;
this.minutes %= 60;
this.seconds %= 60;
},
tick: function() {
var self = this;
setInterval(function(){this.calculateTime()}, 1000);
}
}
countdownTimer.init('02/09/2016');
countdownTimer.calculateTime();
countdownTimer.tick();
Существуют десятки версий этого вопроса на SO, начиная с тех, о тех, о том, как 'this' работает, например [этот] (http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work). –
@torazaburo я понял, что «это» относится к «окну», это было то, что мне пришлось использовать 'bind (this)' –