如何setInterval来调用类中的函数 [英] how do I setInterval to call a function within a class

查看:81
本文介绍了如何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();

但是我似乎无法引用/调用 this.draw() 在setInterval中,它说 this.draw()不是函数,如果我删除引号就说无用的setInterval调用,那是什么我做错了吗?

however I can't seem to reference/call this.draw() within the setInterval, it says this.draw() is not a function, and if I remove the quotes it says useless setInterval call, what am I doing wrong?

推荐答案

这个的值取决于如何调用函数。当您使用 new 调用函数作为构造函数,然后时,将引用正在创建的对象。类似地,当您使用点符号调用函数时,如 run.start()然后将引用运行。但是当 setInterval 运行的代码被称为时,这个并不意味着你的想法。您可以做的是保存对的引用,然后使用该引用,如下所示:

The value of this is set depending on how a function is called. When you call a function as a constructor using new then this will refer to the object being created. Similarly when you call a function with dot notation like run.start() then this will refer to run. But by the time the code run by the setInterval is called this doesn't mean what you think. What you can do is save a reference to this and then use that reference, like the following:

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

另请注意,您已经创建了一个名为的函数运行 一个名为的变量 - 您需要为它们指定不同的名称。在我的代码中(记住JS区分大小写)我已经将函数名称更改为以大写R开头 - 这是打算作为构造函数运行的函数的约定。

Note also that you've created a function called run and a variable called run - you need to give them different names. In my code (bearing in mind that JS is case sensitive) I've changed the function name to start with a capital "R" - which is the convention for functions intended to be run as constructors.

编辑:好的,看看其他答案我可以看到只是可能我过于复杂,而只要 draw()不需要访问这个 它只会说:

OK, looking at the other answers I can see that just maybe I overcomplicated it and as long as draw() doesn't need to access this it would've been fine to just say:

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

但是我的观点仍然没有给你的构造函数和后来的变量同名,我会保留所有 self 内容,因为如果 draw()确实需要访问。如果你要在 draw()函数中添加参数,你也需要这样做。

But my point about not giving your constructor and later variable the same name still stands, and I'll leave all the self stuff in because it is a technique that you will need if draw() does need to access this. You would also need to do it that way if you were to add parameters to the draw() function.

这篇关于如何setInterval来调用类中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆