Native js implementations copy objects and extend objects similar to the extend of method in jquery
- 2020-03-30 03:48:30
- OfStack
Jq's extend () method makes it easy to extend object methods, with the syntax: $.extend (obj1, boj2, obj3);
Now to implement: native js implementation copy object, extension object, similar to the extend() method in jq, the specific example is as follows:
There are 3 object literals:
var o1={hello:1,old:555},
o2 = {
abc: 55555555,
hello: 2,
fun: function() {
alert(111);
}
},
o3={third:9999};
Achieve goals:
Copy the o1 object, extend the object properties and methods of o2 and o3 into the copied object and output.
<script>
var o1={hello:1,old:555},
o2 = {
abc: 55555555,
hello: 2,
fun: function() {
alert(111);
}
},
o3={third:9999};
function cloneObj(oldObj) { //Copy object method
if (typeof(oldObj) != 'object') return oldObj;
if (oldObj == null) return oldObj;
var newObj = new Object();
for (var i in oldObj)
newObj[i] = cloneObj(oldObj[i]);
return newObj;
};
function extendObj() { //Extended object
var args = arguments;
if (args.length < 2) return;
var temp = cloneObj(args[0]); // call Copy object method
for (var n = 1; n < args.length; n++) {
for (var i in args[n]) {
temp[i] = args[n][i];
}
}
return temp;
}
var t=extendObj(o1,o2,o3);
console.log(t);
console.log(o1);
console.log(o2);
console.log(o3);
</script>