簡體   English   中英

我如何setInterval調用類中的函數

[英]how do I setInterval to call a function within a class

我有一個像這樣的課程:

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調用的引號,那我在做什么錯呢?

this設置取決於函數是如何被調用。 當您使用調用一個函數作為構造new ,然后this將涉及到正在創建的對象。 同樣,當您調用帶有點表示法的函數run.start()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則需要使用this 如果要將參數添加到draw()函數,則還需要這樣做。

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> 

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM