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)