ES6 is easier to inherit the use of syntax

Like other object-oriented programming languages, ES6 officially defines the Class class and Extend inherited syntax sugar, and supports static, derived, abstract, iteration, single example, etc., and a lot of interesting usage is derived according to the new features of ES6.

First, the basic definition of the class
Basic all object-oriented languages ​​support class package and inheritance, what is the class?

The class is the basis for object-oriented programming, including

data package, data operation, and functions to transmit messages

. Examples of the class are called objects. The implementation of the simulation class before the ES5 is as follows:

// Constructor Function Person (this) {this.name = Name;} / / Prototype Person.Prototype.SAYNAME = Function () {console.log (this.name);}; // new one instance var Friend = New Person (“jenny”); friend.sayname (); // JennyConsole.log (Friend InstanceOf Person); // TrueConsole.log (Friend InstanceOf Object); // True

 Summary, define a class of ideas as follows:   1. Requires constructor package data 
2. Add method operation data on prototypes, 3. Creating instances

ES6 by New NEW



ES6 defines one using the Class keyword Class, this class has a special method name[[construct]] defines the constructor, which is called when the new creation instance is[[ConstructT]], examples are as follows:

/ * es6 * /// Equivalent to Let Person = Class {Class Person {// Constructor Constructor (Name) {this .name = name;} // Equivalent to Person.Prototype.SayName SayName () {Console.log (this.name);}} console.log (TypeOf Person); // functionconsole.log (TypeOf Person.Prototype. SayName); // FunctionLet Friend = New Person (“jenny”); Friend.SayName (); // jennyconsole.log (Friend InstanceOf Person); // trueconsole.log (Friend InstanceOf Object); // true

 The class defined in the above example is similar to the custom function simulation class function, but it has great differences in nature:   
Function declaration can be improved, but the Class class declaration is similar to lethal;
Class declaration is automatically run in strict mode, “use strict”;

all methods in class They are not enumerated, enumerable is false.
  • Second, a more flexible class
  • The class and function are the first-class citizen of JavaScript (which can be incomplated, returning from the function , Assignment), and notice that the class is moreMore similarities, these features can extend more flexible definitions and use.
  • 2.1 Have the accesser attribute

The attribute of the object has a data attribute and access attribute, and the class can also define the accesser properties through the GET, SET keyword. :

Class Person {Constructor (Name) {this.name = name;} get value () {return this.name + this.age} set value (num) {THIS.AGE = NUM}} let friends = new person (“jenny”); // calling setterfriend.value = 18 // Call is getterconsole.log (Friend.Value) // jenny18


2.2 Calcable member name

Similar to the calculated properties of the ES6 object word spread, class can also be used [expression ] Define the calculated member name, including the method and accessor properties in the class:
   Let methodname = 'SayName' Class Person {constructor (name) {this.name = Name;} [MethodName + 'Default'] () {console.log (this.name);} get [methodname] () {return this.name} set [MethodName] (STR) {this.name =str}} let friend = new Person ( "Jenny"); // Method friend.sayNameDefault (); // Jenny // access properties friend.sayName = 'lee'console.log (friend.sayName) // lee 

For further familiar with the new object characteristics may refer to: new features [ES6] objects and destructuring assignment

2.3 defines the default iterator

 ES6 collection of commonly used objects (arrays, set / Map set) and strings are iterables, if the class is used to represent values ​​of these objects can be iterative, the definition of a default iterator would be more useful.   ES6 generator by adding attributes to Symbol.iterator embodiment, define a default iterator: 


class Person {constructor (name) {this.name = name;} * [Symbol.iterator] () {for (let item of this.name) {yield item}}} var abbrName = new Person (new Set ([ ‘j’, ‘j’, ‘e’, ‘e’, ‘n’, ‘y’, ‘y’, ‘y’,])) for (let x of abbrName) {console.log (x); // jeny} console.log (… abbrName example) // jeny


after the definition of the default iterator class can be used to expand and for-of loop operator (…) functions like iterative.

confused above iterator content may refer to: [ES6] iterators and iterables

2.4 as a type of parameter
   class as "first class citizen" can be used when a parameter passed to the function, of course, also possible to return from the function: 

function createClass (className, val ) {return new className (val)} let person = createClass (Person, ‘Jenny’) console.log (person) // Person {name: ‘Jenny’} console.log (typeof person) // object


2.5 creating a single embodiment

syntax used to create class manner singleton class expressions call immediately by new:
   let singleton = new class {constructor (name) {this.name = name;}} ( 'Jenny') console.log (singleton.name) // Jenny 

here to create an anonymous class expression, then call this new class expressions, and executed immediately by parentheses, like this syntax to create a singleton class is not exposed in the scope of references.

Third, the class inheritance

Recalling how inheritance before ES6? Common way is through the prototype chain, and a combination of inherited constructors like. Class
  ES6 using familiar extendS Keyword Specify the function of the inheritance of the class, and can access the constructor of the parent class via the surpe () method.  
, for example, inherits a Person:

Class Friend Extends Person {Constructor (Name, Phone) {Super (Name) this.Phone = phone} } let myfriend = new friend (‘lee’, 2233) Console.log (myfriend) // Friend {name: ‘lee’, phone: 2233}


Friend inheritance Person, the term is called Person as base class, and Friend is derived.

It is to be noted that surpe () can only be used in derived classes, which is responsible for initializing this, so it is necessary to use Surpe before using this THIS.

3.1 Inheriting the built-in object

The class inherit of ES6 can inherit the built-in object (Array, SET, MAP, etc.) and can have base classes after inheriting All built-in features. For example:
 Class MyArray Extends Array {} Let Arr = New MyArray (1, 2, 3, 4), Subarr = Arr.slice (1, 3) Console. Log (arr.length) // 4console.log (arr instanceof myarray) // trueconsole.log (arr instanceof array) // trueconsole.log (SUBARR  
Note that in the above example, not only the ARR is the instance of derived class MyArray, Subarr is also an instance of derived class MyArray, and the practical use of built-in object inheritance. It is the type of change to the return object.
The browser engine is implemented behind the [Symbol.species] property, which is used to return the static accessory properties of the function, and the built-in object defines the [Symbol.Species] attribute to have Array, ArrayBuffer, SET, MAP, Promise, Regexp, Typed Arrays.

3.2 Inherited expression

Currently Extends can inherit class and built-in objects, but more powerful features export from expressions ! This expression requires that it can be parsed to a function and has[[construct]] attributes and prototypes, as follows:

Function SUP (VAL) { This.Value = VAL} sup.prototype.getval = function () {return ‘Hello’ + this.Value} Class Derived Extends Sup {Constructor (VAL) {Super (VAL)}} Let der = new derived (‘world ” ) Console.log (der) // derived {value: ‘world’} console.log (der.getval ()) // HelloWorld
   
3.3 only Abstract class that can inherit

ES6 introduces the new.target element attribute determination function to call through the New keyword. The constructor of the class can also be called by the new.target to determine how the class is called.

You can create abstract classes (categories that cannot be instantiated) by new.target, for example:


Class Abstract {constructor () {if (New. TARGET === Abstract) {throw new error (‘)’) ‘)’)}}} class instantiable extends Abstract}}}}}}} // let abs = new abstract () // Error: Abstract class (not directly instantified) let abs = new instantiable () console.log (abs instanceof abstract) // true

Although the Abstract abstraction class cannot be used directly Create an instance, but can be derived as a base class.
4, static members
   ES6 declares static members or methods using Static keywords. STATIC can be used before the method or the accesser properties, and the only limit cannot be used for constructive functions. 
The role of static members is the privatization of certain types of members, and cannot be accessed in an instance, and must be accessed directly on the class.

Class Person {Constructor (Name) {this.name = name;} static create (name){Return New Person (Name);}} let beauty = person.create (“jenny”); // beauty.create (‘lee’) // typeerror

If the base class has a static member, these static members can also be used in derived classes.

For example, the above example is used as the base class, and the Friend class is derived and the static method of the base class is used. Create ():
   Class Friend Extends Person {Constructor (Name) {Super (Name)}} var Friend = Friend.create ('lee') console.log (Friend InstanceOf Person) // trueconsole.log (Friend InstanceOf Friend) // False 

It can be seen that the derived class can still use the static method of the base class.

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

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

Please log in to comment