Copy objects and extend objects to implement the extend () method in jquery

Source: Internet
Author: User

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

What we need to implement now is: native js implements copying objects and extension objects, similar to the extend () method in jq. The specific example is as follows:

There are three objects:

The code is as follows: Copy code

Var o1 = {hello: 1, old: 555 },
O2 = {
Abc: 55555555,
Hello: 2,
Fun: function (){
Alert (111 );
}
},
O3 = {third: 9999 };

Goals:

Copy the o1 object and extend the properties and methods of the o2 and o3 objects to the copied objects and output them.

The code is as follows: Copy code

<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 () {// extension object
Var args = arguments;
If (args. length <2) return;
Var temp = cloneObj (args [0]); // call the 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>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.