扩展和深扩展

const _ARRAY_NAME = "[object Array]"
const _OBJECT_NAME = "[object Object]"


//扩展
export function extend(target) {
    var targets, arg = Array.from(arguments).slice(1,arguments.length);
    if(arg.length>0){
        targets = _extend(target,arg[0])
    }
    if(arg.length>1){
        return extend(targets,arg[1])
    }
    return targets;
}


//深扩展

function _extend(target,source) {
    if(_isType(source) ==_ARRAY_NAME){
        for (var i=0;i<source.length;i++){
            if(_isType(source[i]) ==_ARRAY_NAME){
                target[i]=source[i].concat(target[i]?target[i]:[])
                _extend(target[i],source[i])
            }else if (_isType(source[i]) ==_OBJECT_NAME){
                target[i] = target[i]?target[i]:{}
                _extend(target[i],source[i])
            }else {
                target[i] = source[i]
            }
        }
    }else {
        for (var v in source){
            if(_isType(source[v]) ==_ARRAY_NAME){
                target[v]=source[v].concat(target[v]?target[v]:[])
                _extend(target[v],source[v])
            }else if(_isType(source[v]) ==_OBJECT_NAME){
                target[v] = target[v]?target[v]:{}
                _extend(target[v],source[v])
            }else {
                target[v] = source[v]
            }
        }
    }
    return target;
}

function _isType(obj) {
    return Object.prototype.toString.call(obj)
}

  

posted @ 2017-07-31 15:17  小结巴巴吧  阅读(207)  评论(0编辑  收藏  举报