setInerval 的使用注意事项(JavaScript)


;( function () {

// 中介者模式


window . Game = function () {

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

this . start ();

}
Game . prototype . start = function () {
var self = 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值