代码
function deep() {
var length = arguments.length;
if (length <= 2) {
if (length === 1) {
return deep({}, arguments[0]);
}
else if (length === 2) {
deepCopy(arguments[0],arguments[1]);
}
else {
return {};
}
}
else {
for (var i = 1; i < length; i++) {
deepCopy(arguments[0],arguments[i]);
}
}
return arguments[0];
function deepCopy(newObj,oldObj) {
for (var i in oldObj) {
if (typeof oldObj[i] === 'object') {
if (oldObj[i].constructor === Array) {
newObj[i] = [];
}
else if (oldObj[i] instanceof HTMLElement || oldObj[i] === window) {
newObj[i] = oldObj[i];
}
else {
if(!newObj[i] || !(newObj[i] instanceof Object)) {
newObj[i] = {};
}
}
deepCopy(newObj[i],oldObj[i]);
}
else {
newObj[i] = oldObj[i];
}
}
return newObj;
}
}
使用方法
- deep(a,b) 返回扩展后的a对象,a对象有b对象的所有属性值
- deep({},a,b)返回一个新对象,新对象包括a对象和b对象的所有属性值,有相同属性时b对象的会覆盖a对象,后面的对象优先级高,可以传多个对象