JavaScript Object-Oriented Programming-object copy for quickly building inheritance relationships

Source: Internet
Author: User

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



Related Article

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.