Understanding _javascript Techniques for JavaScript inheritance

Source: Internet
Author: User

Since JavaScript primitives do not support classes (ES6 already supports class and extends), not to mention inheritance, polymorphism, and in order to simulate some of these features of other object-oriented programming languages, Daniel has written a way to achieve this by reading John Resig's Simple JavaScript Inheritance "This article, was deeply impressed, the original dozens of lines of JavaScript can be so powerful, elegant, the following in my understanding of the way to read."

The main implementation of the inheritance, access to the parent class of the duplicate method (here is a wonderful way to implement), but unfortunately can not implement the member variable/function hidden.

(function () {  //set flag bit, is in the process of new A () or B=a.extends ({/*  /});   var initializing = False,       //fntest desirable result for two regular objects/\b_super\b/and/.*/       //when the regular test method parameter supports automatic invocation of the ToString () method, take the preceding       fntest =/xyz/.test (function () { XYZ;}) ?
/\b_super\b/:/.*/;        //Create a global class object   this.
Class = function () {};        //Create an inheritance function   class.extend = function (prop) {    //
Here the _super point to the prototype of the parent class, which needs to be used to determine whether the parent or child has the same method     var _super = This.prototype;            //start B=a.extends ({/*  /})   
  initializing = true;
    //instantiate the parent class and give the instance method and attributes of the parent class to prototype     var prototype = new This ();
    initializing = false;     //End B=a.extends ({/*   *)            // Iterate through the user's incoming objects for building subclasses     //processing includes:     //1, attributes are stored directly to prototype      //2, the method does not call the method of the same name in the parent class by This._super (), then the method is saved directly to the prototype     //3, there is a pass in the method This._super () to invoke the method of the same name in the parent class, wrap the following procedure into a function to prototype:     //   point the This._super to the same method as the parent class, It then calls the subclass's method and returns the execution result     for (var name in prop) {The       //loop body looks slightly complicated is the essence of the whole code.       //simplified This process is   V = a && b && c? D:e; Equal to V = (a && b && c)? D:e       //This process is mainly used in the logical operation of the short-circuit operation A,b,c all true V=d, otherwise v=e        //a to determine whether Prop[name] is a function, B to determine whether the parent class also has the name function with the same names, C mainly to determine whether the name function has the same method of calling the parent class (that is, called This._super ())        //D is when A,b,c is satisfied at the same time, that is to say: Name is a function, and the name function exists in the parent class, and the subclass's name function needs to call the parent class'sName function       //If one of the a,b,c is not satisfied then direct Prop[name] to Prototype[name]        prototype[name] = typeof Prop[name] = = "function" &&        
 typeof _super[name] = = "function" && fntest.test (prop[name))?          (function (name, FN) {           //first, the prerequisite determines prototype[name] is a function, so wrap a function to return to            return function () {            //The author backs up here, Then invoke FN and then restore This._super             // Because return is a function that has a delay call, this always points to the subclass itself when the subclass invokes FN              //and here the _super is the _super of the parent class, it has nothing to do with This._super, so the backup should be redundant              //var tmp = this._sUper;             //this._super point to the parent class method with the same name as FN (i.e. Prop[name]) To facilitate the internal invocation of FN             //here is the implementation subclass via This._super ()
The key             this._super = _super[name] that invokes a function of the same name as the parent class;             //the subclass at this point, and the this._super inside the subclass already points to a function with the same name as the parent class , i.e. _super[name]             var ret = fn.apply (This, arguments);                //this._
Super = TMP;             //Return execution Results      
       return ret;
          };        &NBSP}) (name, Prop[name]):    &NBsp;    prop[name];    &NBSP}            //this "class" and the "class" outside It's two things.     //This class is actually a constructor of a subclass     function class () {       //is not a a.extends ({/*   * *}) process       if (!initializing
&& this.init)         this.init.apply (this, arguments);    &NBSP}            //
The prototype     class.prototype of the prototype bound to the subclass of the preceding process = prototype;            //Fixed constructor     
Class.prototype.constructor = Class;          //to give subclasses the ability to continue inheriting     class.extend =
Arguments.callee;
           return Class;
  }; })();

If you want to learn more about JS inheritance, continue to view the 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.