我有一堂课,比如:
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 调用,我做错了什么?
The bind() method!
请参阅以下示例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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)