In-depth understanding of JavaScript series (45): code reuse mode (avoid Article)

Source: Internet
Author: User
Tags hasownproperty

introduce any programming code reuse, otherwise, every time a new program or write a new feature to be written new, then the rest of the dish, but the code reuse is also good to bad, the next two articles we will be for code reuse for discussion, the first article to avoid the article, means to avoid the use of these patterns as much as possible, because there are more or less problems, the second row is recommended, refers to the recommended mode of use, generally will not have any problems. Mode 1: default mode code multiplexing the default pattern that is commonly used is often problematic, using the constructor of parent () to create an object and assign the object to the prototype of child (). Let's look at the code:functioninherit (C, P) {c.prototype=NewP ();}//Parent ConstructorfunctionParent (name) { this. Name = Name | | ' Adam ';}//adding say functionality to prototypesParent.prototype.say =function () {    return  this. name;};//child constructor is emptyfunctionchild (name) {}//Perform inheritanceInherit (child, Parent);varKid =Newchild (); console.log (kid.say ());//"Adam"varKiddo =Newchild (); Kiddo.name= "Patrick"; Console.log (kiddo.say ());//"Patrick"//cons: cannot allow parameters to be passed into child constructorsvars =NewChild (' Seth '); console.log (s.say ()); //"Adam"The disadvantage of this model is that the child cannot pass in the parameter, basically also is Obsolete. Pattern 2: Borrowing a constructor this pattern is the child borrows the Parent's constructor for apply, and then passes the Child's this and arguments to the Apply method://Parent ConstructorfunctionParent (name) { this. Name = Name | | ' Adam ';}//adding say functionality to prototypesParent.prototype.say =function () {    return  this. name;};//child Constructorfunctionchild (name) {parent.apply ( this, arguments);}varKid =NewChild ("Patrick"); Console.log (kid.name); //"Patrick"//cons: no say method inherited from constructorsConsole.log (typeofkid.say);//"undefined"The disadvantage is also obvious, the Say method is not available because there is no inheritance. Mode 3: borrowing constructors and setting up prototypes both of these patterns have their own shortcomings, how to remove the shortcomings of both, let's try://Parent ConstructorfunctionParent (name) { this. Name = Name | | ' Adam ';}//adding say functionality to prototypesParent.prototype.say =function () {    return  this. name;};//child Constructorfunctionchild (name) {parent.apply ( this, arguments);} Child.prototype=NewParent ();varKid =NewChild ("Patrick"); Console.log (kid.name); //"Patrick"Console.log (typeofkid.say);//functionConsole.log (kid.say ());//PatrickConsole.dir (kid);Deletekid.name;console.log (kid.say ());//"Adam"run, everything is fine, but there is no discovery, the parent constructor executes two times, so that although the program is available, it is Inefficient. Pattern 4: shared prototype shared prototype refers to the same prototype used by child and parent, with the following code:functioninherit (C, P) {c.prototype=p.prototype;}//Parent ConstructorfunctionParent (name) { this. Name = Name | | ' Adam ';}//adding say functionality to prototypesParent.prototype.say =function () {    return  this. name;};//child Constructorfunctionchild (name) {}inherit (child, Parent);varKid =NewChild (' Patrick '); Console.log (kid.name); //undefinedConsole.log (typeofkid.say);//functionKid.name = ' Patrick '; Console.log (kid.say ());//PatrickConsole.dir (kid); OK or the same, Child's parameters are not received Correctly. Pattern 5: The temporary constructor first borrows the constructor, then sets the Child's prototype to the instance of the borrowed constructor, and finally restores the child Prototype's Constructor. The code is as Follows:/*Closed Package*/varInherit = (function () {    varF =function () {    }; return function(C, P) {f.prototype=p.prototype; C.prototype=NewF (); C.uber=p.prototype; C.prototype.constructor=C; }} ());functionParent (name) { this. Name = Name | | ' Adam ';}//adding say functionality to prototypesParent.prototype.say =function () {    return  this. name;};//child Constructorfunctionchild (name) {}inherit (child, Parent);varKid =Newchild (); console.log (kid.name);//undefinedConsole.log (typeofkid.say);//functionKid.name = ' Patrick '; Console.log (kid.say ());//PatrickvarKid2 =NewChild ("Tom"); console.log (kid.say ()); Console.log (kid.constructor.name); // childConsole.log (kid.constructor = = = Parent);//falseas usual, child cannot receive parameters Properly. Mode 6:klass This mode, first on the code bar:varKlass =function(Parent, Props) {varchild , F, i; //1.    //New ConstructorsChild =function () {        if(child.uber && Child.uber.hasOwnProperty ("__construct") {child.uber.__construct.apply ( this, arguments); }        if(Child.prototype.hasOwnProperty ("__construct") {child.prototype.__construct.apply ( this, arguments);    }    }; //2.    //InheritanceParent = Parent | |Object; F=function () {    }; F.prototype=parent.prototype; Child.prototype=NewF (); Child.uber=parent.prototype; Child.prototype.constructor=child ; //3.    //add an implementation method     for(iinchProps) {        if(props.hasownproperty (I)) {child.prototype[i]=props[i]; }    }    //return the "class"    returnchild ;};varMan = Klass (NULL, {__construct:function(what) {console.log ("man ' s constructor");  this. Name =what ; }, getName:function () {        return  this. name; }});varFirst =NewMan (' Adam ');//logs "man ' s constructor"First.getname ();//"Adam"varSuperman =Klass (man, {__construct:function(what) {console.log ("superman ' s constructor"); }, getName:function () {        varName = SuperMan.uber.getName.call ( this); return"I am" +name; }});varClark =NewSuperman (' Clark Kent ')); Clark.getname (); //"I am Clark Kent"Console.log (clarkinstanceofman);//trueConsole.log (clarkinstanceofsuperman);//trueHow about that? Looking at is not a bit dizzy, say well, the pattern of grammar and Specification twist and other languages, you are willing to use it? Cough... Summing up the above six models although in some special circumstances to achieve some functions, but there are shortcomings, so the general situation, we should avoid the Use. Reference: http://Shichuan.github.com/javascript-patterns/#code-reuse-patternssynchronization and recommendation this article has been synchronized to the directory Index: in-depth understanding of JavaScript series in-depth understanding of the JavaScript series, including the original, translation, reprint and other types of articles, if it is useful to you, please recommend supporting a, to the power of the Uncle Writing. 

In-depth understanding of JavaScript series (45): code reuse mode (avoid Article)

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.