如何设置间隔来调用类中的函数
我有一个像这样的类:
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 调用,我做错了什么?
I have a class like:
function run(){
this.interval;
this.start = function(){
this.interval = setInterval('this.draw()',1000);
};
this.draw = function(){
//some code
};} var run = new run(); run.start();
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
bind() 方法!
请参阅 ES6 中的以下示例:
The bind() method!
See the following example in ES6:
this
的值根据函数的调用方式进行设置。当您使用new
将函数作为构造函数调用时,this
将引用正在创建的对象。类似地,当您调用带有点符号的函数(例如run.start()
)时,this
将引用run
。但是,当setInterval
运行的代码被调用时,this
并不意味着您的想法。您可以做的就是保存对this
的引用,然后使用该引用,如下所示:另请注意,您已经创建了一个名为
run
的函数 and< /em> 一个名为run
的变量 - 您需要为它们指定不同的名称。在我的代码中(请记住 JS 区分大小写),我已将函数名称更改为以大写“R”开头 - 这是旨在作为构造函数运行的函数的约定。编辑:好的,看看其他答案,我可以看到,也许我把它弄得太复杂了,只要
draw()
不需要访问this
直接说就可以了:但是我关于不给构造函数和后来的变量使用相同名称的观点仍然有效,并且我将保留所有
self 东西,因为这是一种你需要的技术,如果
draw()
确实需要访问this
。如果您要向draw()
函数添加参数,您也需要这样做。The value of
this
is set depending on how a function is called. When you call a function as a constructor usingnew
thenthis
will refer to the object being created. Similarly when you call a function with dot notation likerun.start()
thenthis
will refer torun
. But by the time the code run by thesetInterval
is calledthis
doesn't mean what you think. What you can do is save a reference tothis
and then use that reference, like the following:Note also that you've created a function called
run
and a variable calledrun
- 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.EDIT: OK, looking at the other answers I can see that just maybe I overcomplicated it and as long as
draw()
doesn't need to accessthis
it would've been fine to just say: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 ifdraw()
does need to accessthis
. You would also need to do it that way if you were to add parameters to thedraw()
function.