首页 > 代码库 > js对象深潜拷贝(从requirejs中抠出来的)

js对象深潜拷贝(从requirejs中抠出来的)

 1 var op = Object.prototype, 2     ostring = op.toString, 3     hasOwn = op.hasOwnProperty; 4  5 function isFunction(it) { 6     return ostring.call(it) === ‘[object Function]‘; 7 }; 8  9 function isArray(it) {10     return ostring.call(it) === ‘[object Array]‘;11 };12 function hasProp(obj, prop) {13     return hasOwn.call(obj, prop);14 };15 function eachProp(obj, func) {16     var prop;17     for (prop in obj) {18         if (hasProp(obj, prop)) {19             if (func(obj[prop], prop)) {20                 break;21             }22         }23     }24 };25 /**26  * Simple function to mix in properties from source into target,27  * but only if target does not already have a property of the same name.28  *29  * @param {target} 目标对象30  * @param {source} 源对象31  * @param {force} 是否强制覆盖目标对象已有的属性32  * @param {deepStringMixin} 是否深拷贝递归操作33  *34  * @returns {target}35  */36 function mixin(target, source, force, deepStringMixin) {37     if (source) {38         eachProp(source, function (value, prop) {39             if (force || !hasProp(target, prop)) {40                 if (deepStringMixin && typeof value =http://www.mamicode.com/== ‘object‘ && value &&"color: #008080;">41                     !isArray(value) && !isFunction(value) &&42                     !(value instanceof RegExp)) {43 44                     if (!target[prop]) {45                         target[prop] = {};46                     }47                     mixin(target[prop], value, force, deepStringMixin);48                 } else {49                     target[prop] = value;50                 }51             }52         });53     }54     return target;55 };56 57 58 调用:59 var obj = {60     name:‘Tom‘,61     age:19,62     children:{63         name:‘Jack‘,64         age:3065     }66 };67 var obj2 = mixin({},obj,false,true);68 obj.children.name=‘Marry‘;69 console.log(obj2);

 

js对象深潜拷贝(从requirejs中抠出来的)