How is the class in ES6 implementation (detailed ES5 code compiled by Babel)


This article mainly explains one of the problems in the interview – the implementation of the Class syntax in ES6?

ECMAScript 6 implements Class, Class is a syntax, making JS clearer, more humane, closer to object-oriented feelings; also makes IDE, compile type inspector, code style check Tools such as instruments are more convenient to detect code syntax and do static analysis. Similarly, this is a lower threshold to contact JS with a software development engineer who is shortcoming.

ES5 Code for ES6 Class

The traditional method of JavaScript language is to define and generate new objects by constructing function, such a way of writing and traditional object-oriented objects. The language difference is large. So, ES6 introduces the concept of Class, as a template for the object.

Effect: ES6 Create a Class will add a constructor method by default, and automatically calls the method when the NEW call is called.
ES5:

Function Person (Name, AGE) {this.name = Name; this.Prototype.toString = Function () {return ‘(‘ + this.name + ‘)’;} var p = new person (‘MIA’, 18); console.log (p); // person { Name: ‘MIA’, AGE: 18}

ES6:
   Class Person {Constructor (Name, AGE) {this.name = Name; THIS.AGE = AGE;} TOSTRING () {Return '(' + this.name + ',' + THIS.AGE + ')'; }} VAR P = New Person ('MIA', 18); Console.log (P); // Person {Name: 'MIA', AGE: 18} 

The constructor in the class of ES6 is a constructor, corresponding to the constructor in the ES5, and the THIS keyword represents an instance object.
The Class class inside can be seen as another way to construct a function, by typeof person === ‘function’ is true; persot === person.prototype.constructor is true, class The data type is a function, and the class itself points to the constructor. It can also be said that the bottom layer of the class is still the function constructor.
 The public method of the class is defined on the Prototype property in the class. You can add multiple methods to classes using Object.Assign once.  Special: The internal definition of the Class is unconcerned, which is inconsistent with the ES5 behavior.  ES5: 
Object.keys (Person.Prototype); // [‘toString’]

ES6:

Object.keys (Person.ProtoTYPE); // Person {}

Unuuseable code implementation will be parsed after the ES6 code is subjected to Babel transcoding.
   
Effect: The Class class must use the new call, otherwise it will be reported.

 Person () // Undefined   
ES6:

Person () // TypeError: Class Constructionor Person Cannot Be Invoked WitHout ‘New’
Example of attributes

Effect: The attribute of the instance is explicitly defined on the THIS object, otherwise it is defined on the prototype. All instances of the class share a prototype object, which is consistent with ES5 behavior.

ES5:

Function Person () {this.grade = {count: 0};}
   

Class Person {Constructor () {this.grade = {count: 0};}}
   
Furthermore, pay attention to the new proposal, Babel has supported instance properties and new aims of static attributes.
Static method


The class is equivalent to the prototype of the instance, all methods defined in the class, will be inherited by the instance. If you add a Static keyword before one method, it means that the method will not be inherited by the instance, but is called directly through the class, which is called a “static method”.

Note: If the static method contains this keyword, it means a class.

ES5:

Function Person () {} person.tosay = function () {return ‘i love javascript.’;}; Person;}; person.tosay (); // i love javascript.
 ES6:   
Class Person {static tosay () {Return ‘I love javascript.’;}} Person.tosay (); // i love javascript.

Getter and setter
  ES6 provides GET and SET keywords, setting values ​​function and value functions for an attribute, intercepting access behavior of this property, and ES5 behavior.  ES5: 
Function Person (Name) {} Person.Prototype = {Get Name () {return ‘mia’;}, set name NEWNAME) {Console.log (‘new name:’ + newname);}}

ES6:

Class Person {Get Name () {Return ‘MIA’;} Set name (new name) {Console.log (‘new name:’ + newname); }}

ES6 Class underlying Realization Principle

The following mainly uses a Babel transcoder to several in Class. The main method is transcoded and analyzes the implementation of ES5.
  Babel is how to compile the class of  
The following code uses the babel transcoder to convert ES5 codes, to explain in accordance with the code structure and function block .

Class Person {Constructor (Name, AGE) {this.name = name; THIS.AGE = Age;} Tostring () {return ‘(‘ + this.name + ‘,’ + this.age + ‘)’;}} var P = New Person (‘MIA’, 18);
   Operation mode 
“Use Strict”; // Class defaults to turn on strict mode

Private function:

JS developer is prefixed in variable name or function name prefix to add a line, generally said private .

The prefix is ​​equipped with a crowd indicating that the private is just a conventional habit, clarifying the intentions, and does not do other processing. Since the process of private variables are not defined in the draft draft draft, it can still be outside the function or outside of the field below.Access the function or variable.

   
Check if the Class class of the declared Class class is called by the New, otherwise the error will be reported.

Function _INSTANCEOF (LEFT, Right) {IF (Right! = Null && TypeOf Symbol! == “undefined” && right [symbol.hasinstance]) {RTURN RIGHT [ Symbol.hasInstance] (left);} else {return left instanceof right;}} function _classCallCheck (instance, Constructor) {if {throw new TypeError ( “Can not call a class as a function” (_instanceof (instance, Constructor)!) (}}

_CREATECLASS and _DEFINEPROPERTIES function
   _createClass function has three parameters, and constructor is incoming constructor Person The protoprops is a function array to be added to the prototype, and StaticProps is the function of the constructor itself, that is, the static method. The second and third parameters here are the default, and will be judged in the _createClass function. 
_CREATECLASS function The role of function is to collect public functions and static methods, add methods to constructor or constructor, and return constructor.

DefineProperties is the primary logic of the method to the prototype of the constructor or constructor, traversing a function array, and declare its descriptor. If Enumerable is not defined as true, the default is FALS, set configurable to true. The above two Boolean values ​​are traversed in order to limit the method such as Object.keys (). If you exist, add a value and write attribute to Descriptor. If you don’t exist, you will use the GET and SET properties directly. Finally, use the Object.defineProperty method to add attributes to constructor.

Function_DefineProperties (Target, Props) {for (var i = 0; i

Class class implementation

var Person = / * # __ PURE __ * / function () {function Person (name, age) {_classCallCheck (this, Person); this.name = name ; this.age = age;} _createClass (Person, [{key: “toString”, value: function toString () {return ‘(‘ + this.name + ‘,’ + this.age + ‘)’;}} ]); Return Person;} (); var p = new Person (‘MIA’, 18);
  Analysis: 
When the New is called, this point points to Window, so instance instanceof constructor is False, throwing an exception.

Traverse the function array by calling the _createclass function. Key is the name of the method, if there is Value description, there is a specific Function declaration, if there is no Value, use the GET or SET method.

End

Read this to believe that everyone has a deeper understanding of the implementation of Class. Recently, the author sorted out the analysis of this Ali front end interview questions while taking it out, and the comment area welcomed the discussion of Class implementation. In addition, Extend in Class is also an interesting implementation, in the next article, inherits the Class implementation.

The above is all the content of this article, I hope to help everyone, I hope everyone will support Tumi Cloud.

© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment