JavaScript Object-Oriented Programming-object copy for quickly building inheritance relationships
In the preceding example, we create an object through the constructor and want the object to inherit from another constructor. We can also directly target an object to achieve the purpose of inheritance, using the following steps: 1. Copy an object. 2. Add attributes to the new object.
/*** Copy the attributes and behavior of the inherited Object * @ param {Object} p parent Object */function extendCopy (p) {var c = {}; for (var I in p) {c [I] = p [I];} c. uber = p; return c ;}
It is also relatively simple to use:
Var shape = {name: 'shape', toString: function () {return this. name ;}} var twoDee = extendCopy (shape); twoDee. name = '2d shape'; twoDee. toString = function () {return this. uber. toString () + ',' + this. name ;}; var triangle = extendCopy (twoDee); triangle. name = 'angle '; Triangle. getArea = function () {return this. side * this. height/2;} // use the inherited toString method alert (triangle. toString ());
For deep copy, you can use the following function:
/*** Deep copy * @ param {Object} p parent Object * @ param {Object} c sub-Object */function deepCopy (p, c) {var c = c | {}; for (var I in p) {if (typeof p [I] = 'object ') {c [I] = (p [I]. constructor === Array )? []: {}; DeepCopy (p [I], c [I]);} else {c [I] = p [I] ;}} return c ;}