Class inheritance in ES6 and inheritance patterns in ES5

Source: Internet
Author: User
1. Inheritance mode in ES5

Let's look at the inheritance in ES5 first.

Since we want to implement inheritance, first we have to have a parent class.

function {    Console.log (this. Name + ' eating ' + food );            }  function Animal (name) {    this. color = [' green ', ' red ', ' Blue '];      this. Name = name | | ' Animal ';      This function () {        Console.log (this. Name + "Sleeping")    }} 
1.1. Prototype chain inheritance

The prototype chain inherits the core: the instance of the parent class is used as a prototype of the child class.

function Cat (name) {    this. Name = name    this. color = [' green ', ' red ', ' Blue '];   Reference type value, and all instances share this property. new Animal ();   var New Cat (' Cat '); Console.log (cat.name); Console.log (cat.eat (' fish 'instanceof  Animal); Console.log (Cat.sleep ());

The prototype chain inheritance pattern implements the child class inheritance of the parent class's prototype.

However, the prototype chained inheritance does not implement code reuse , some common properties: such as name, in subclasses still have to write again (that is, the same set of code will have to be re-written).

Furthermore, cat inherits all the properties and methods of the animal instance, not all of which we need, that is, too many inherited unused properties. And if the prototype contains reference type values , then all instances share this property.

1.2. Constructor mode

Constructor Mode Core: calls a super-type constructor inside a subtype constructor.

function Person (name,age,sex) {    this. Name = name;      this. Age = Age ;     this. Sex = sex;} function Student (name,age,sex) {    Person.call (this, name,age,sex);     this. Grade =new Student;

Advantages:

    • Constructor pattern inheritance implements code reuse

Disadvantages:

    • The prototype of a borrowed constructor cannot be inherited, only the properties and methods of the constructor itself can be borrowed
    • Each constructor takes one more function.
1.3. Combination Inheritance

implementation of the core: the combination of inheritance combined with the above two modes of inheritance, that is, the implementation of code reuse, but also the implementation of the prototype inheritance.

functionsupertype (name) { This. Name =name;  This. colors = [' Red ', ' blue ', ' Pink '];} SuperType.prototype.sayName=function() {Console.log ( This. name);}functionSubtype (name,age) {//Inheritance PropertiesSupertype.call ( This, name);//Call Supertype The second time you create an instance     This. Age =Age ;}//Inheritance MethodSubtype.prototype =NewSupertype ();//call supertype for the first timeSubType.prototype.constructor = subtype; SubType.prototype.sayAge=function() {Console.log ( This. Age)}

Disadvantages:

    • The parent constructor is called 2 times, and the attribute of the subclass instance is two, one on the prototype and one on the instance property. Cause a waste of memory.
1.4. Parasitic combined inheritance

Parasitic combined inheritance is a further optimization of combinatorial inheritance. Let's take a look at why we're writing this statement.

New Supertype ();

We're just trying to get subtype to inherit Supertype's prototype. But why don't we just write it that way?

Subtype.prototype = Supertype.prototype

It is indeed possible to implement the subclass object's inheritance of the parent class object prototype. But in this case, all the prototypes of the subclass objects that inherit the parent class are pointing to the same one . That is to say, subtype cannot have its own prototype. This is obviously not what we want.

Since it is not possible to inherit directly, could it indirectly inherit Supertype.prototype? This is the final solution: parasitic combined inheritance .

Let's get a function to point to Supertype.prototype, and then let Subtype.prototype point to the object that the function produces.

functioninherit (target,origin) {//core function to implement parasitic combined inheritance functionF () {}; F.prototype= Origin.prototype;//The prototype of F () points to OriginTarget.prototype =NewF ();//Target's prototype is pointing to F ()Target.prototype.constructor =Target;
subtype.prototype.__proto__ = = Supertype.prototype}functionsupertype (name) { This. Name =name; This. colors = [' Red ', ' blue ', ' Pink '];} SuperType.prototype.sayName=function() {Console.log ( This. name);}functionSubtype (name,age) {//Inheritance PropertiesSupertype.call ( This, name);//Call Supertype The second time you create an instance This. Age =Age ;} Inherit (subtype,supertype);//implementing parasitic combined inheritance

Let's take a look at the core function that implements parasitic combined inheritance. The F function is actually generic, and we don't need to declare it every time we enter the inherit function. So we can write in the form of closures:

varInherit = (function () {        varF =function () {}; return function(Target, Origin) {F.prototype= Origin.prototype;//The prototype of F () points to OriginTarget.prototype =NewF ();//Target's prototype is pointing to F ()Target.prototype.constructor =Target; Target.prototype.uber=Origin.prototype;
subtype.prototype.__proto__ = = Supertype.prototype}}) ()
2. Class inheritance in ES6

Let's take a look at how the ES6 defines a class.

class Parent {    Constructor (name,age) {        this. Name = name;          this. Age = Age ;    }        GetName () {        returnthis. Name;    }}
Functions, the data type of a class is a function, and the class itself points to the constructor

The above code defines a "class", and you can see that there is a constructor method in it, which is the constructor method, and the This keyword represents the instance object. That is, the ES5 constructor, parent, corresponds to the constructor of the parent class of the ES6.
In addition to constructing methods, the parent class defines a GetName method.

Note that when you define a "class" method, you do not need to precede the keyword with function, and you can simply put the definition of the functions in it. In addition, the method does not need a comma separation, plus will error . All methods defined in a class are non-enumerable .

Also: all methods of the class are defined above the prototype property of the class . The class does not have a variable elevation , and if called before the class declaration, an error is raised.

New parent (); class Parent {    Constructor (name,age) {        this. Name = name;          this. Age = Age ;    }        GetName () {        returnthis. Name;    }} // uncaught referenceerror:parent is not defined
2.1. Constructor method of Class

The constructor method is the default method for the class, which is called automatically when an object instance is generated from the new command. A class must have a constructor method,

if not explicitly defined, an empty constructor method is added by default .

2.2. Inheritance of Classes
class Child extends Parent {    constructor (sex) {        super ();         this. Sex = sex;            }} var New Child (' Xiaoyu ', ' n ', ' man ');

In the constructor of a subclass, if the display declares constructor, the call to the Super function must be displayed (this is a bit different from Java).

You can use the This keyword only after you call super, or you will get an error.

2.3. Prototype properties and __proto__ properties for classes

In the ES5 implementation of most browsers, each object has a __proto__ property that points to the prototype property of the corresponding constructor.

Class is the syntactic sugar of the constructor, with both the prototype attribute and the __proto__ attribute, so there are two inheritance chains at the same time.

    • The __proto__ property of the subclass, which represents the inheritance of the constructor, always points to the parent class.
    • The __proto__ property of the subclass prototype property, which represents the inheritance of the method, always points to the prototype property of the parent class.

These characteristics are identical to the parasitic combined inheritance of ES5, so the inheritance of class can be regarded as the syntactic sugar (simple comprehension) of parasitic combined inheritance. but actually the underlying principle of the two implementations is completely different. because Ruan a peak of the book "ES6 Basic" inside that ES6 inheritance mechanism completely and ES5 inheritance mechanism is different. That's what Nanyi's Big book says.

ES5 's inheritance, in essence, is to create an instance object of the subclass this, and then add the method of the parent class to this above (parent.apply (this)). The inheritance mechanism of ES6 is completely different, essentially creating an instance object of the parent class (so the super method must be called first), and then modifying this with the constructor of the subclass.

So the small partners who have a deep understanding of this can talk about their own understanding. Progress together.

Write here first, and then continue adding if there is more understanding.

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.