2011-10-29 21 views
4

我有一類像中調用一個函數:我怎麼setInterval的一類

function run(){ 
this.interval; 
this.start = function(){ 
    this.interval = setInterval('this.draw()',1000); 
}; 
this.draw = function(){ 
    //some code 
};} var run = new run(); run.start(); 

但是我似乎無法引用/ setInterval的在中調用this.draw(),它說:this.draw()不是一個函數,如果我刪除引號它說無用的setInterval調用,我做錯了什麼?

回答

10

this的值取決於函數的調用方式。當您使用new作爲構造函數調用函數時,則this將引用正在創建的對象。同樣,當您使用點符號(如run.start())調用函數時,則this將引用run。但是到setInterval運行的代碼被稱爲this並不意味着您的想法。你可以做一個參考保存到this,然後使用該引用,如下所示:

function Run(){ 
    var self = this; 

    self.start = function(){ 
    self.interval = setInterval(function() { self.draw(); },1000); 
    }; 

    self.draw = function(){ 
    //some code 
    }; 
} 

var run = new Run(); 

run.start(); 

還請注意,你已經創建了一個名爲run功能的變量稱爲run - 你需要給他們不同的名字。在我的代碼中(記住JS區分大小寫),我已經將函數名稱更改爲以大寫「R」開始 - 這是用於作爲構造函數運行的函數的約定。

編輯:好的,看着其他的答案我可以看到,只是也許我過於複雜,並只要draw()並不需要訪問this它會一直罰款,只是說:

this.interval = setInterval(this.draw, 1000); 

但我對不給你的構造函數和變量後的同名問題依然存在,我會離開所有self東西在,因爲它是,如果draw()確實需要訪問this,你將需要的技術。如果要將參數添加到draw()函數中,您還需要這樣做。

+2

'this.draw'將無法正常工作,如果'draw'需要正確的'this'裏面,當'畫'在'setInterval(this.draw,1000)'版本中調用,''這個''將在'draw'內部是'window'。如果'draw'使用實例屬性(即,如果它確實是一種方法而不僅僅是一個普通函數),那麼所有'self'東西都是必需的。 –

+1

是的。當我添加我的「編輯」時,我只是看着'draw'包含可能不需要'this'的一些代碼,但如果它不這樣,它可能不是一個非常有用的方法,所以...我將編輯我的編輯... – nnnnnn

+0

感謝您的回答,刪除引號和()工作,然後我注意到每次間隔運行繪圖函數內部的變量都是未定義的!那麼我把一切都設定爲自我,一切都解決了,但是,我仍然不明白爲什麼以及如何運作,你介意多給點解釋一下嗎?再次感謝。 :)哦好吧,所以這指向窗口內的setInterval,如何WEIRD!無論如何,有沒有更好的方式做到這一點,自我看起來不正確:\ – fenerlitk

-2
function run(){ 
    this.interval; 
    this.start = function(){ 
     this.interval = setInterval(this.draw,1000); 
    }; 
    this.draw = function(){ 
     //some code 
    } 
;} 

var run = new run(); 
run.start(); 
6

bind()方法!

ES6下面的例子:

<!DOCTYPE html> 
 
<html> 
 

 
<body> 
 
    <canvas id="canvas" width="200" height="200" style="border: 1px solid black"></canvas> 
 

 
    <script> 
 
     class Circles { 
 
      constructor(canvas, r = 5, color = 'red') { 
 
       this.ctx = canvas.getContext('2d') 
 
       this.width = canvas.width 
 
       this.height = canvas.height 
 

 
       this.r = r 
 
       this.color = color 
 

 
       setInterval(
 
        this.draw.bind(this), 
 
        1000 
 
       ) 
 
      } 
 

 
      draw() { 
 
       this.ctx.fillStyle = this.color 
 

 
       this.ctx.beginPath() 
 
       this.ctx.arc(
 
        Math.random() * this.width, 
 
        Math.random() * this.height, 
 
        this.r, 
 
        0, 
 
        2 * Math.PI 
 
       ) 
 

 
       this.ctx.fill() 
 
      } 
 
     } 
 
    </script> 
 

 
    <script> 
 
     var canvas = document.querySelector('#canvas') 
 
     var circles = new Circles(canvas) 
 
    </script> 
 
</body> 
 

 
</html>

+0

爲什麼這沒有更多upvotes? –