Es6 inheritance vs JS native inheritance (ES5)

Source: Internet
Author: User

Recently looking at some of es2015 's grammar, the most practical thing is to inherit this new feature. For example, the following code:

1$(function(){2 class father{3 Constructor (name, age) {4               This. Name =name;5               This. Age =Age ;6         }7 8 Show () {9Console.log (' My Name: ${ This. Name}, this year ${ This. Age} years old ');Ten         } One     }; A class Son extends father{}; -  -Let son =NewSon (' Golden Horn King ', 200); the son.show ();//return My name: King Horn, 200 years old this year -  -});

This is one of the simplest inheritance. In the son class, there is no own property and method, look at the structure in the F12

is also no exception to the use of the prototype chain to implement the inheritance, then in the ES5 if you want to implement this inheritance what should be done?

Use Babel to translate this code into ES5 syntax and find the code as follows:

1"Use Strict";2 3 var_createclass =function() {functionDefineproperties (target, props) { for(vari = 0; i < props.length; i++) {varDescriptor = Props[i]; descriptor.enumerable = Descriptor.enumerable | |false; Descriptor.configurable =true;if("Value"inchDescriptor) Descriptor.writable =true; Object.defineproperty (target, Descriptor.key, descriptor); } }return function(Constructor, Protoprops, Staticprops) {if(protoprops) defineproperties (Constructor.prototype, protoprops);if(staticprops) defineproperties (Constructor, staticprops);returnConstructor;}; }();4 5 function_possibleconstructorreturn (self, call) {if(!self) {Throw NewReferenceerror ("This hasn ' t been initialised-super () hasn ' t been called"); }returnCall && (typeofCall = = = "Object" | |typeofCall = = = "function")?call:self;}6 7 function_inherits (subclass, superclass) {if(typeofSuperclass!== "function" && superclass!==NULL) {Throw NewTypeError ("Super expression must either is null or a function, not" +typeofSuperclass); } Subclass.prototype = object.create (Superclass && Superclass.prototype, {constructor: {value:subclass, Enumer Ablefalse, writable:true, Configurable:true} });if(superclass) Object.setprototypeof? Object.setprototypeof (subclass, superclass): subclass.__proto__ =superclass;}8 9 function_classcallcheck (instance, Constructor) {if(! (InstanceinstanceofConstructor)) {Throw NewTypeError ("Cannot call a class as a function"); } }Ten  One /** A * Created by Liuyc14 on 2016/6/28. -  */ -  the varFather =function () { -     functionFather (name, age) { -_classcallcheck ( This, Father); -  +          This. Name =name; -          This. Age =Age ; +     } A  at _createclass (Father, [{ -Key: "Show", -ValuefunctionShow () { -Console.log ("I Call:" + This. Name + ", this year" + This. Age + "year old"); -         } -     }]); in  -     returnFather; to }(); +  - ; the  * varSon =function(_father) { $ _inherits (Son, _father);Panax Notoginseng  -     functionSon () { the_classcallcheck ( This, Son); +  A         return_possibleconstructorreturn ( This, Object.getprototypeof (Son). Apply ( This, arguments)); the     } +  -     returnSon; $ } (Father); $  -;

These are the implementation codes for the ES5 syntax generated after the completion of the Babel compilation, which seems to be a lot more.

Don't worry, pick out a few points to see ( later examples use ES5 syntax )

1. _createclass method, create a class, use the Defineproperties method, which is to give the target object of the first parameter, append all properties of the second parameter

2. The _inherits method, which implements the core of the inheritance, uses the object.create and object.setprototypeof methods

Object.create Method:

This method takes two parameters, the first parameter is the object to inherit , the second parameter is an attached property , and returns a created object.

As an example:

1 functionFather (name, age) {2      This. Name =name;3      This. Age =Age ;4 }5 6Father.prototype.show =function () {7Console.log (' I call: ' + This. name+ ', this year ' + This. age+ ' Years ');8 };9 Ten varobj =object.create (father.prototype); OneConsole.log (Obj.name);//return undefined AObj.show ();//return my name: Undefined, undefined year old

In this example, using the Create method, an Obj object is created, and the object inherits the properties of the Father.prototype object. (There is only one Show method, and there is no name and age attribute)

Seeing this function, we can use the Create method to implement ES5 inheritance.

1 functionFather (name, age) {2      This. Name =name;3      This. Age =Age ;4 }5 6Father.prototype.show =function () {7Console.log (' I call: ' + This. name+ ', this year ' + This. age+ ' Years ');8 };9 Ten functionSon (name, age) { OneFather.call ( This, name, age); A } -Son.prototype =object.create (father.prototype); -Son.prototype.constructor =Son; theSon.prototype.show =function () { -Console.log (' I'm a subclass, my name ' + This. Name + ', this year ' + This. Age + ' old '); - }; - vars =NewSon (' Silver Horn King ', 150); //return, I'm a sub-class, my name is Silver Horn King, 150 years old this year  +S.show ();

The above son class, when defined, uses father.call to inherit Father's instance properties, using the Object.create method to inherit Father's prototype, thus fully implementing the inheritance, and looking at the analysis diagram

Son's instance, S, has its own show method in the prototype, then looks up the prototype of the father, and can see the prototype of show, a clear hierarchy

In fact, we can not use the Object.create method, using the Object.setprototypeof method instead, to achieve the same effect

The 13th line of code in the previous example

Son.prototype = Object.create (Father.prototype); =
Object.setprototypeof (Son.prototype, Father.prototype);

The two lines of code have the same effect, and the second method is more intuitive, that is, son.prototype.__proto__ = Father.prototype .

Last question, how can we call the parent class in a subtype in C # or Java? such as Son.prototype.show=function () {super.show ()}

You can use the object.getprototypeof (Son.prototype) method to get the top level of the prototype chain so that you can get to the Father.prototype object and then call the show () method

1 function () {2    object.getprototypeof (Son.prototype). Show (); 3      This this. Age + ' old '); 4 };

But call son's Show method, will log out: I called: Undefined, this year undefined years old; I'm a subclass, my name is Silver Horn King, 150 years old this year.

Why do you have undefined? Look at our F12 structure diagram, there is no name and age attribute in Father.prototype, what should I do? Use the call method Ah!

The Complete class inheritance implementation code is posted below:

1 functionFather (name, age) {2      This. Name =name;3      This. Age =Age ;4 }5 6Father.prototype.show =function () {7Console.log (' I call: ' + This. name+ ', this year ' + This. age+ ' Years ');8 };9 Ten functionSon (name, age) { OneFather.call ( This, name, age); A } - object.setprototypeof (Son.prototype, father.prototype); -Son.prototype.constructor =Son; theSon.prototype. $super = object.getprototypeof (Son.prototype);//Use the $super property to point to the prototype of the parent class -Son.prototype.show =function () { -      This. $super. Show.call ( This); -Console.log (' I'm a subclass, my name ' + This. Name + ', this year ' + This. Age + ' old '); + }; - vars =NewSon (' Silver Horn King ', 150); +S.show ();

OK, today's summary is finished, like Journal, everyone live to see it

Es6 inheritance vs JS native inheritance (ES5)

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.