Learn the "original type inheritance" of Douglas crockford"

Source: Internet
Author: User

In JavaScript advancedProgramBoth Design (version 2nd) and JavaScript language ExtractCode:

Object. beget = function (o) {function f () {}; F. Prototype = O; return new F ;};

A temporary constructor is defined in the function. The parameter O of the function is the input object, which is assigned to the prototype of the constructor. Then, the instance is returned. Essentially, the input object executes a shap copy.

Advantage: you do not need to create constructors.

Disadvantage: attributes of the reference type share their values.

How can this problem be solved? In Chapter 4th of JavaScript design patterns, childobject creates a reference type value using the factory method:

VaR compoundobject ={}; compoundobject. createchildobject = function () {return {num: [10] };} compound. childobject = compoundobject. createchildobject (); var compoundobjectclone = object. beget (compoundobject); compoundobjectclone. childobject = compoundobject. createchildobject (); compoundobjectclone. childobject. num = [5];

Childobject is the sub-object of compoundobject. The Return Value of the createchildobject () method of compoundobject is assigned to it. Compoundobjectclone is the object of compoundobject's "original type inheritance". Its Attributes in childobject are re-assigned.

(End)

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.