日期:2014-05-16  浏览次数:20312 次

extjs源码分析-012(Funtion扩展)
Ext.apply(Function.prototype, {
     //创建拦截器,也就是在函数执行想运行拦截器,当拦截器返回false则不往下执行
      /*var sayHi = function(name){
       alert('Hi, ' + name);
     }
     var sayHiToFriend = sayHi.createInterceptor(function(name){
       return name == 'Brian';
     });     
     */
     createInterceptor : function(fcn, scope){
        var method = this;
        return !Ext.isFunction(fcn) ?
                this :
                function() {
                    var me = this,
                        args = arguments;
                    fcn.target = me;
                    fcn.method = method;
                    return (fcn.apply(scope || me || window, args) !== false) ?
                            method.apply(me || window, args) :
                            null;
                };
    },
    //创建回调函数
    /*
    var sayHi = function(name){
       alert('Hi, ' + name);
    }
    sayHi.createCallback('Fred')
    */
    createCallback : function(/*args...*/){
        // make args available, in function below
        var args = arguments,
            method = this;
        return function() {
            return method.apply(window, args);
        };
    },
    //委派
    createDelegate : function(obj, args, appendArgs){
        var method = this;
        return function() {
            var callArgs = args || arguments;
            if (appendArgs === true){
                callArgs = Array.prototype.slice.call(arguments, 0);
                callArgs = callArgs.concat(args);
            }else if (Ext.isNumber(appendArgs)){
                callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
                var applyArgs = [appendArgs, 0].concat(args); // create method call params
                Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
            }
            return method.apply(obj || window, callArgs);
        };
    },
    //延迟执行
    /* 
   var sayHi = function(name){
     alert('Hi, ' + name);
   }
   sayHi.defer(2000, this, ['Fred']);
    */
    //millis毫秒数,args调用函数的参数,appendArgs附加参数
    defer : function(millis, obj, args, appendArgs){
        var fn = this.createDelegate(obj, args, appendArgs);
        if(millis > 0){
            return setTimeout(fn, millis);
        }
        fn();
        return 0;
    },
    //创建队列函数,
    createSequence : function(fcn, scope){
        var method = this;
        return !Ext.isFunction(fcn) ?
                this :
                function(){
                    var retval = method.apply(this || window, arguments);
                    fcn.apply(scope || this || window, arguments);
                    return retval;
                };
    }
})