JavaScript Object-oriented programming (10) Quickly build object copies of inheritance relationships

Source: Internet
Author: User

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

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.