in the previous example, we created the object through the constructor and wanted the object to inherit objects from another constructor.we can also directly target an object to achieve the purpose of inheritance, using subordinate steps:1. Copy an object 2. Adding attributes to new objects
/** * Inherit properties and behavior of an object by copying * @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's also easier 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 = ' triangle '; triangle.getarea = function () {return this.side * THIS.HEIGHT/2;} Use the inherited ToString method alert (triangle.tostring ());
For deep copies, 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)? []: {};d eepcopy (P[i], c[i]);} else {C[i] = P[i];}} return c;}
JavaScript Object-oriented programming (10) Quickly build object copies of inheritance relationships