2016-09-01 6 views
0

他の投稿から収集したものは不可能ですが、なぜこのようなsetInterval関数(わずかに短い手)を呼び出すことができませんか?OOPスタイルのJSはsetInterval関数では動作しません

tick: function() { 
    var self = this; 
    setInterval(this.calculateTime, 1000); 
} 

私は以下を使用する必要があります。

tick: function() { 
    var self = this; 
    setInterval(function(){this.calculateTime()}, 1000); 
    } 

誰にもこれが当てはまる理由を説明してもらいたいと思いますか?

あなたがあなたの目的のためにbindを使用することができます

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(); 
+0

ように、この質問のバージョンの数十の方法については、それらについてのものと始まる、がありますこれは[this one](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work)のように動作します。 –

+0

@torazaburo私は 'これは'ウィンドウ 'と呼ばれることを理解し、それは私が'バインド(これ) 'を使用しなければならなかった –

答えて

0

の下に完全なコードを参照してください。

setInterval(this.calculateTime.bind(this), 1000); 
+0

thats Christoph、良い知識です!私ができるときあなたに緑のダニを与えるだろう –

+0

彼はそれを行う方法を尋ねなかった。彼はなぜそれが必要なのか尋ねました。 –

+0

@ torazaburo私は質問にどのように答えたのか非常に満足していました –

関連する問題