`
mxyzdl1234
  • 浏览: 3455 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

setTimeout使用中响应方法里的this引用乱指

阅读更多
    今天修改Ext源码时,使用了setTimeout方法,setTimeout(func,ms)其中func方法中的this引用指向的居然是windows,并不是源对象的引用,而且给func方法传参数很是麻烦,经过与同事沟通,了解到Ext也有相应的延迟任务的api,其源码如下:
Ext.util.DelayedTask = function(fn, scope, args){
    var me = this,
        id,     
        call = function(){
            clearInterval(id);
            id = null;
            fn.apply(scope, args || []);
        };
 
    me.delay = function(delay, newFn, newScope, newArgs){
        me.cancel();
        fn = newFn || fn;
        scope = newScope || scope;
        args = newArgs || args;
        id = setInterval(call, delay);
    };
 
    me.cancel = function(){
        if(id){
            clearInterval(id);
            id = null;
        }
    };
}; 

其中第二个参数 scope,决定了响应方法fn中的this引用到底指向谁,而且如果想向fn中传入参数,可以使用第三个参数,以数组的形式[..]想传多少个参数就传多少个参数,很方便。
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics