Some ideas on JS inheritance

Source: Internet
Author: User
Tags es6 class

Some ideas on JS inheritance

The inheritance of JS before Es6 is multifarious. It is also a bit awkward to use object-oriented writing in the project, and more often it feels that the process-oriented writing is simpler and more efficient. Over time, the inheritance of JS will understand difficulties every once in a while. So this time I want to write down the understanding of the object, so it should be a bit deeper.

Let's start by looking at how an object is generated.

//Three ways to create objectsvarObj= {}varObj2= New Object()varObj3= Object.Create(NULL)//Create an empty string objectvarObj4= New String()obj.Constructor === Obj2.Constructor        //Trueobj.__proto__ === Obj2.__proto__ === Object.prototype       //TrueObj4.__proto__ === String.prototype         //TrueObj4.__proto__.__proto__ === Object.prototype   //Ture

These three methods, the first two are the same. The empty objects they create have prototypes, and the third creates a really empty object that does not inherit any attributes, and Obj4 is a string object. Look at the contrast:
The following object, in addition to OBJ3, has a __proto__ implicit property that points to the prototype of the constructor that created the instance.

Here obj and obj2 are empty objects, but they have a method of the properties of the object constructor, and Obj4, in addition to the properties and methods owned by OBJ, has properties and methods owned by string, and Obj3 is a real empty object, its __proto__ The point is null.

Let's start obj4 all over again:

Then look at the relationship between them:

For example, I would like to cite the two native constructors of object and string. Their relationship is the same as the relationship between the parent class and the subclass that we normally write, and all of the classes will eventually point to object.

In the age of ES5, the simplest inheritance we use is the prototype chain that inherits

//We first create a parent classfunction Super(name){   This.name =Name This.type = ' I am the parent '}Super.prototype.Move = function(){  Console.Log( This.name + ' Running ')}//Subclass Inherits parent classfunction  Child(name){   This.name =Name} Child.prototype = New Super()//prototype chain inheritance, the private methods and properties of the subclass prototype are added after inheritance, otherwise they will be overwritten Child.prototype.Constructor =Child//fix a point to the constructor Child.prototype.Eat = function(){   //Do something}

The prototype chain inheritance is the prototype of the subclass equal to the instance of the parent class, and then the properties and methods of the subclass prototype are added. The disadvantage is that only one parent class can be inherited. And when you create an instance of a subclass, you cannot pass the argument to the parent class. This is the best choice when doing a single inheritance and the parent does not need to pass the argument.

Here is an introduction to a kind of inheritance that I personally think is already very good (combination inheritance)

//subclass inherits Parent class   child  (name) { super . call  (this ) this . name  =  name}  child . prototype  =  new  super  () child . prototype . constructor  =  Child //fixes a pointer to the constructor  child . prototype . eat  =  function  () { //do something  }   
  • This inheritance is a rude way of using the parent super constructor to copy the instance properties of the parent class into the subclass in such a way that the object is impersonating. Inherits the properties and methods of the parent prototype in a way that inherits from the stereotype.
  • This way of inheriting, you will find that the properties of the instance of the subclass and __proto__ have the properties of the parent class, and the subclass instance of the class prototype is overwritten.
  • This way, you can implement inheritance for multiple parent classes (non-prototype parts). Because the inheritance of prototypes is chained, only one can be inherited.

In general, this kind of inheritance is very good, the code is small. The inheritance is good, the malpractice also has no influence. This is the inheritance before ES6. Let's take a look at how ES6 operates.

ES6 's Class
  • ES6 provides a more similar approach to traditional languages, introducing the concept of class as a template for objects. You can define classes by using the class keyword.
  • Basically, ES6 class can be regarded as just a syntactic sugar, its most functions, ES5 can do, the new class writing is just to make the object prototype more clear, more like object-oriented programming syntax. The above code is rewritten with the ES6 class, which is the following.

These two sentences refer to Nanyi's introduction to ES6 's Class (the basic syntax of Class). Nandashin's ECMAScript 6 primer is really a must-have for the ES6 beginner at home. I'll talk about my understanding right here.

//write a classclassPoint{  Constructor(x,Y{     This.x =X;     This.y =Y;  }  toString(){    return '(' +  This.x + ', ' +  This.y + ')';  }}varPoint= New  Point(2, 3)//New one instance

Below to see what is inside the point, you can see that constructor,tostring are in the "Proto" inside.

What is the equivalent of the constructor in this case?

//write a classfunction  Point(x,Y{   This.x =X This.y =Y} Point.prototype.toString = function(){  return '(' +  This.x + ', ' +  This.y + ')';}varPoint= New  Point(2, 3)//New one instance

Without considering the class static attribute, it can be simply understood that the new property and method under this constructor are within the constructor, and the method outside the constructor is prototype.

  • Look at the inheritance of class.
classChildpointextendsPoint{  Constructor(x,Y,Z{    Super(x,Y This.Z =Z}  toString(){    return '(' +  This.x + ', ' +  This.y + ','+  This.Z +')';  }  Changex(x){     This.x =X}}varChildpoint= New Childpoint(2, 3, 4)//New instance of a ChildpointConsole.Log(Childpoint.x)//2Console.Log(Childpoint.y)//3Console.Log(Childpoint.Z)//4Console.Log(Childpoint.toString())//2,3,4Childpoint.Changex(5)Console.Log(Childpoint.x)//5Console.Log(Childpoint.__proto__ === Childpoint.prototype)//TrueConsole.Log(Childpoint.__proto__.__proto__ ===  Point.prototype)//TrueConsole.Log(Childpoint.Constructor ===Childpoint)//True

Here class inherits the parent class through extends, and the constructor method of the subclass needs to call the super () method, which is quite the same as calling the parent class's constructor () method.

The following is a look at the internal situation of Childpoint:

As can be seen from the picture and the above print, es6 inheritance and combinatorial inheritance are very similar. The only difference is that the inheritance of ES6 does not have an extra copy of the instance attribute generated by the combination of inheritance in the prototype. Looks very pleasing to the eye. However, the relative es6 cannot inherit more (although the combined inheritance can inherit more than one constructor, and cannot inherit multiple prototypes).

In fact, the combination of inheritance can also be further upgraded to ES6 inherit that look (parasitic combination inheritance):

//We first create a parent classfunction Super(name){   This.name =Name This.type = ' I am the parent '}Super.prototype.Move = function(){  Console.Log( This.name + ' Running ')}//Subclass Inherits parent classfunction  Child(name){  Super.Pager( This) This.name =Name}(function(){  //Create an intermediate class with no super instance  varMiddlesuper= function(){}  Middlesuper.prototype = Super.Prototyoe       //share prototypes with Super  //Here the difference between Middlesuper and super is that there are no instances.   //And then in the normal combination of inherited operations   Child.prototype = New Middlesuper()})() Child.prototype.Constructor =Child//fix a point to the constructor Child.prototype.Eat = function(){   //Do something}

After a series of complicated operations, we got a structure like ES6. But ES6 only need a extends, and es6 before we have to long-winded writing to achieve, but also particularly around. So in a word, learn es6 quickly.

  • This article is purely personal opinion, please point out any questions.

This article refers to the following:

  • The realization of the JS inheritance of the Magic Day mans
  • Nanyi's ECMAScript 6 Getting Started

Some ideas on 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.