Home > Web Front-end > JS Tutorial > body text

Native js realizes copying objects and extending objects, similar to the extend() method in jquery_javascript skills

WBOY
Release: 2016-05-16 16:38:27
Original
1177 people have browsed it

The extend() method of jq can easily implement the extended object method. The syntax is as follows: $.extend(obj1,boj2,obj3);

What needs to be implemented now is: native js implements copying objects and extending objects, similar to the extend() method in jq. The specific examples are as follows:
There are currently 3 object literals:

var o1={hello:1,old:555},
o2 = {
abc: 55555555,
hello: 2,
fun: function() {
alert(111);
}
},
o3={third:9999};
Copy after login

Goal achieved:

Copy the o1 object, extend the object properties and methods of o2 and o3 into the previously copied object and output it.

<script>
var o1={hello:1,old:555},
o2 = {
abc: 55555555,
hello: 2,
fun: function() {
alert(111);
}
},
o3={third:9999};
function cloneObj(oldObj) { //复制对象方法
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() { //扩展对象
var args = arguments;
if (args.length < 2) return;
var temp = cloneObj(args[0]); //调用复制对象方法
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>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!