当前位置:Gxlcms > JavaScript > 在jquery中实现深拷贝与浅拷贝

在jquery中实现深拷贝与浅拷贝

时间:2021-07-01 10:21:17 帮助过:29人阅读


var toString = [].toString,
    hasOwn = Object.prototype.hasOwnProperty;var types = {    
    '[object Boolean]':'bool',    
    '[object Number]' : 'number',  
        '[object String]' : 'string',  
    '[object Object]':'object',    
    '[object Array]':'array',    
    '[object Function]':'function',    
    '[object Date]' : 'date', 
            '[object RegExp]' : 'regExp',  
};var type = function(obj){
    return obj === null ? String(obj) : types[toString.call(obj)] || 'object'; 
};var isWindow = function(obj){
    return obj && typeof obj === 'object' && 'setInterval' in obj;
};var isArray = Array.isArray || function(obj){
    return type(obj) === 'array';
};var isPlainObject = function(obj){
    if(!obj || type(obj) !== 'object' || isWindow(obj) || obj.nodeType){        
    return false;
    }    
    try{        
    if(obj.constructor && !hasOwn.call(obj, 'constructor') 
            && !hasOwn.call(obj.constructor.prototype, 'isPrototypeOf')){            
            return false;
        }
    }catch(e){        
    return false
    }    
    var key;    for(key in obj){}    return key === undefined || hasOwn.call(obj, key)
}function extend(deep, target, ref){
    var name, value, src, copy, clone, copyIsArray;    for(name in ref){
        src = target[name];
        copy = ref[name];        
        if(target === copy){            
        continue;
        }        
        if(deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))){            
        if(copyIsArray){
                clone = src && isArray(src) ? src : [];
            }else{
                clone = src && isPlainObject(src) ? src : {}; 
            }
            target[name] = extend(deep,clone,copy);
        }else{
            target[name] = copy;
        }
    }    return target;
}function extend2(target, ref){
    var name, value;    
    for(name in ref){
        value = ref[name];        
        if(value !== undefined){
            target[name] = value;
        }
    }    return target;
}

以上就是在jquery中实现深拷贝与浅拷贝的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行