Javascript 如何设置在类中调用函数的间隔
我有一门课,像:Javascript 如何设置在类中调用函数的间隔,javascript,scope,settimeout,Javascript,Scope,Settimeout,我有一门课,像: 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(
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
调用函数作为构造函数时,此
将引用正在创建的对象。类似地,当您使用点符号调用函数时,如run.start()
,则此
将引用run
。但是当setInterval
运行的代码被称为this
时,它并不代表您的想法。您可以做的是保存对该的引用,然后使用该引用,如下所示:
function run(){
this.interval;
this.start = function(){
this.interval = setInterval(this.draw,1000);
};
this.draw = function(){
//some code
}
;}
var run = new run();
run.start();
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.interval = setInterval(this.draw, 1000);
但我关于不给构造函数和以后的变量取相同名称的观点仍然有效,我将保留所有self
内容,因为如果draw()
确实需要访问this
,这是一种需要的技术。如果要将参数添加到draw()
函数中,也需要这样做。方法
请参见ES6中的以下示例:
阶级圈子{
构造函数(画布,r=5,颜色为“红色”){
this.ctx=canvas.getContext('2d')
this.width=canvas.width
this.height=canvas.height
这个。r=r
这个颜色
设定间隔(
这个.画.绑(这个),,
1000
)
}
画(){
this.ctx.fillStyle=this.color
this.ctx.beginPath()
这个是.ctx.arc(
Math.random()*this.width,
Math.random()*this.height,
这个,r,,
0,
2*Math.PI
)
this.ctx.fill()
}
}
var canvas=document.querySelector(“#canvas”)
变量圆=新圆(画布)
this.draw
如果draw
需要正确的this
内部,则当draw
在setInterval(this.draw,1000)
版本中被调用时,this
将成为窗口内部draw
。如果draw
使用实例属性(即,如果它确实是一个方法而不仅仅是一个普通函数),则所有self
内容都是必需的。True。当我添加我的“编辑”时,我正在查看包含“一些代码”的draw
,这些代码可能不需要this
,但如果不需要,它可能不会是一个非常有用的方法,因此…我将编辑我的编辑…感谢您的回答,删除了引号,并且(),然后我注意到每次运行间隔时,draw函数中的变量都没有定义!然后我把一切都设置为self,一切都解决了,但是,我仍然不明白这是为什么和如何工作的,你介意再解释一下吗?再次感谢。:)哦,好吧,这指向设置间隔内的窗口,真奇怪!无论如何,有没有更好的方法来做到这一点,self在我看来并不正确:\n你不必把变量称为“self”,但从语义上讲,它就是这样的。有些人会说“我”之类的话。很多人说“那个”,但我讨厌“那个”,因为它在语义上是错误的(“这个”和“那个”不应该是同一件事)。不管你叫它什么,尽管这个概念仍然是最好的方法(据我所知)。有关“this”如何工作的更多信息,请查看(或者只需谷歌“javascript this”并查看结果)。@NickSteele可能是因为它在每次间隔调用draw()
之前都会导致额外的函数调用?我同意Yas的解决方案更具可读性。