js函数封装缺省值使用

js封装函数如需传递参数arguments,那么缺省值如何使用呢?
如果封装一个http请求函数:

/*可变参数:*/
url:String,
method:String,
data:Object,
callback:Function,
error:Function

function ajaxConstruct(){
    /* 假定默认参数顺序 url method data callback error*/
    var d = {
      url:'',
      method:'',
      data:null,
      callback:function(){},
      error:function(){}
    }

    //我的思路是 利用扩展来赋值
    var params = arguments;//获取所有实际入参
    _params = deepClone({},d,params||{}); 

    ...执行ajax函数体↓↓↓

}

ajaxConstruct(obj1);


//自执行扩展函数
!(function (global) {
    var extend,
        _extend,
        _isObject;
    _isObject = function (o) {
        return Object.prototype.toString.call(o) === '[object Object]';
    };
    _extend = function self(destination, source) {
        var property;
        for (property in destination) {
            if (destination.hasOwnProperty(property)) {
                if (_isObject(destination[property]) && _isObject(source[property])) {
                    self(destination[property], source[property]);
                }
                if (source.hasOwnProperty(property)) {
                    continue;
                } else {
                    source[property] = destination[property];
                }
            }
        }
    };
    extend = function () {
        var arr = arguments,
            result = {},
            i;
        if (!arr.length)
            return {};
        for (i = arr.length - 1; i >= 0; i--) {
            if (_isObject(arr[i])) {
                _extend(arr[i], result);
            }
        }
        arr[0] = result;
        return result;
    };
    global.deepClone = extend;
})(window);

另一种情况是顺序字符串参数,如何封装缺省值函数呢?

1.对于既定函数,须定义所有入参顺序
2.对于可能存在省略的入参进行数据类型判定

function (url, data, callback, type) {
    // shift arguments if data argument was omitted
    if (typeof(data)==='function') {
        type = type || callback;
        callback = data;
        data = undefined;
    }

    return function(){
        //url, data, callback
    };

    //data type conversion if data type was Incomed error
    String();    
    Object.toString();
    Boolean();
    Number();
    Array();
    Date();
}

 

你可能感兴趣的:(大前端开发)