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> |