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

时间:2023-03-09 16:04:06
js对象深潜拷贝(从requirejs中抠出来的)
 var op = Object.prototype,
ostring = op.toString,
hasOwn = op.hasOwnProperty; function isFunction(it) {
return ostring.call(it) === '[object Function]';
}; function isArray(it) {
return ostring.call(it) === '[object Array]';
};
function hasProp(obj, prop) {
return hasOwn.call(obj, prop);
};
function eachProp(obj, func) {
var prop;
for (prop in obj) {
if (hasProp(obj, prop)) {
if (func(obj[prop], prop)) {
break;
}
}
}
};
/**
* Simple function to mix in properties from source into target,
* but only if target does not already have a property of the same name.
*
* @param {target} 目标对象
* @param {source} 源对象
* @param {force} 是否强制覆盖目标对象已有的属性
* @param {deepStringMixin} 是否深拷贝递归操作
*
* @returns {target}
*/
function mixin(target, source, force, deepStringMixin) {
if (source) {
eachProp(source, function (value, prop) {
if (force || !hasProp(target, prop)) {
if (deepStringMixin && typeof value === 'object' && value &&
!isArray(value) && !isFunction(value) &&
!(value instanceof RegExp)) { if (!target[prop]) {
target[prop] = {};
}
mixin(target[prop], value, force, deepStringMixin);
} else {
target[prop] = value;
}
}
});
}
return target;
}; 调用:
var obj = {
name:'Tom',
age:19,
children:{
name:'Jack',
age:30
}
};
var obj2 = mixin({},obj,false,true);
obj.children.name='Marry';
console.log(obj2);