setInerval 的使用注意事项(JavaScript)

来源:互联网 发布:linux打开3306端口 编辑:程序博客网 时间:2024/06/09 09:23

;(function() {

//中介者模式


window.Game= function() {

this.canvas= document.getElementsByTagName("canvas")[0];
this.ctx= this.canvas.getContext("2d");

this.start();

}
Game.prototype.start= function() {
varself=this;
//方式一
setInterval(function() {
self.mainLoop()

},20);
//方式2
setInterval(self.mainLoop,20);

};//end start
Game.prototype.mainLoop= function() {
console.log("我是主循环")

}
})();

上面通过两种方式实现了在循环调用mainLoop方法,但是这两种方式有一个重要的区别:
(1)第一中方式
var self = this;
//方式一
setInterval(function () {
self.mainLoop()

}, 20);
注意这里的mainLoop是被self调用的,这个self也就是调用start方法的那个对象。

(2)第二种方式中,我们是将mainLoop函数引用传递给了setInterval方法,所以该mianLoop方法中的this表示的 是window对象,而不是当前对象,这是两者的区别。
0 0