"In-depth JavaScript" a method of JS inheritance

Source: Internet
Author: User

These days read John Resig's "Secrets of JavaScript Ninja", which discusses the implementation of JS in the scheme of inheritance, very interesting, I explored a bit, formed a note, put here.

This program is also on the Resig blog, although the code is slightly inconsistent, but the core idea is the same, please poke here.

//Call a immediate funciton,prevent global namespace from being polluted.(function(){        //This initializing variable is used to identify whether the class is currently in the initial creation phase, and the following continues to detail        varinitializing =false,        //This is a tricky notation for detecting whether a function can be serialized in the current environment        //attach an article to discuss function serialization: Http://www.cnblogs.com/ziyunfei/archive/2012/12/04/2799603.html        //Superpattern refers to a regular object that is used to verify that the _super method is used in the validated functionSuperpattern =/xyz/.test (function() {xyz;}) ? /\b_super\b/:/.*/; Object.subclass=function(properties) {//prototype object for the current object (parent class)            var_super = This. prototype; //initializing = True indicates that the class is currently in its initial creation phase.             //the This constructor determines the state of the initializing and, if False, does not execute the Init method.             //In fact, this is also very much needed because at this point, all we need is a clean, fictional constructor that does not need to execute the INIT function to avoid contamination. The Init method needs to be executed only when the current class is instantiated, and the inheritance behavior is currently being performed, and the Init method should not be executed. initializing =true; //an instance object of the current object (parent class)            varProto =New  This(); //the initial creation phase is complete and the initializing is falseinitializing =false; //The property provided in properties, as the public property of the current object (parent Class) instance, is shared by its subclass instances;            //The method provided in properties, as the public method of the instance of the current object (parent class), is shared by its subclass instances.              for(varNameinchproperties) {Proto[name]=typeofProperties[name] = = ' function ' &&//detects whether the currently provided is a function                              typeof_super[name] = = ' function ' &&//detects whether the currently provided function name already exists in the prototype object of the parent class, and if so, the following action is required to ensure that the method in the parent class is not overwritten and can be called in some way, and if no, the method that assigns the function directly to the parent class instanceSuperpattern.test (Properties[name])? F//detects if the _super method is used within the currently provided function, and if there is a _super method, the following action is required to ensure that the method in the parent class is not overwritten and can be called in some way, and if the _super method is not used, the function is directly assigned to the method of the parent class instance. Even if the parent prototype already has a method with the same name (overwrite)                    //using a function that executes immediately, returns a closure so that each closure refers to its own name and FN. (function(name, FN) {return function() {                            //The _super property of the current object (the instantiated object of the subclass) of the executing method is first saved to the TMP variable.                             //this is necessary because this always points to the object that is currently being called.                             //The following operation is important when C inherits B,b A, and a\b\c has a dance method and B\c dance method uses This._super to refer to the methods of their parent class. It allows This._super to always point to the same name method in the prototype of the parent class of the "current class" When the method is called, thus avoiding this._super being arbitrarily rewritten.                             varTMP = This. _super; //The same-name method in the parent class's prototype is then assigned to This._super so that the instantiated object of the subclass can use the method that already exists in the corresponding parent class prototype when it executes the name method This._super                             This. _super =_super[name]; //executes the function provided when the subclass is created and passes in the parameter through arguments                            varret = fn.apply ( This, arguments); //re-assign the _super property saved in TMP back to This._super                             This. _super =tmp; //returns the execution result of a function                            returnret;                    };            }) (name, Properties[name]): Properties[name]; }            //A class named class is defined internally, and there is only one action inside the constructor: Execute the Init method that may exist in the current object            //the reason for this: Create a new Class (closure), can prevent a lot of interference (detailed contrast JS Advanced Design third Edition)            functionClass () {//if inheritance is not being implemented and the Init method of the current class exists, the Init method is executed                //each time the subclass method executes, it returns the class constructor, which is executed when the user uses the new method .                //Essence: Create a new Class (closure) for each call to subclass                if(!initializing && This. Init) {                    //This is the initialization method of the subclass, in which you can define the private properties of the subclass, and the public properties should be added at the top of the                     This. init.apply ( This, arguments); }            }            //rewrite the class constructor's prototype so that it no longer points to the class native prototype object, but instead points to Proto, an instance of the current object (class)            //Essence: The prototype of one class is an instance of another class (inheritance)Class.prototype =Proto; //why rewrite the constructor of class? Because of this class function, its original constructor points to a function object, where it corrects its point and makes it point to itself. Class.constructor =Class; //This is the operation, so that each call to subclass will be a new life class object, also has the subclass method, can continue to be inherited            //essence: Enables each subclass of inheritance to have the ability to inheritClass.subclass =Arguments.callee; //returns the newly defined internal constructor (closure)            returnClass;    };    })(); varperson =Object.subclass ({init:function(isdancing) { This. Dancing =isdancing; }, Dance:function() {Console.log (' I am a person,i dance. '); return  This. Dancing;    }    }); varNinja =Person.subclass ({init:function() {}, Dance:function() {Console.log (' I am an ninja,i dance. ');  This. _super (); return; }, Swingsword:function(){            return true;    }    }); varChileung =Ninja.subclass ({dance:function() {Console.log (' I am chileung.i dance. ');  This. _super (); return;    }    }); varp =NewPerson ();    P.dance (); varn =NewNinja ();    N.dance (); varc =NewChileung (); C.dance ();</script></body>

In the blog Park also found a good in the discussion of this way of succession, see here

In addition, I have also thought about the Zakas proposed succession plan, the article see here

"In-depth JavaScript" a method of JS inheritance

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.