Definition of a, ES6 class
ES5 write constructor method:
function Point(x, y) { this.x = x; this.y = y; }
ES6 introduced Class (category), by class
the keyword can be defined class.
class Point { constructor(x, y) { this.x = x; this.y = y; } }
Here, the constructor for ES6 Point Point class constructor corresponding to the front ES5, the code constructor
is a constructor.
About constructor
constructor
Class is the default method, bynew
generating a command object instance, the method is automatically invoked.There must be a class
constructor
method, if no explicit definition, an emptyconstructor
method will be included by default:Point {class } // equivalent to the class Point { constructor () {} }
Examples of two, ES6 class
Examples of generated classes and ES5, just as with the new
command.
But without new instance constructor can also be performed, but with the new class must, otherwise it will error:
Point {class // ... } // given var Point = Point (2,. 3 ); // correct var Point = new new Point (2,. 3);
Three, ES6 class inheritance
1, extends keyword inheritance
class Parent{ constructor(lastName='Liu'){ this.lastName=lastName; } } class Child extends Parent{ } console.log(new Child()); // 输出结果
2, super () method to pass parameters Inherited
class Parent{ constructor(lastName='Liu'){ this.lastName=lastName; } } class Child extends Parent{ constructor(lastName){ super(lastName); } } console.log(new Child('Chen')); // 输出结果
Four, getter and setter
And ES5 as in-house "class" can use the get and set keywords, set the value of the function and stored-value function for a property, blocking access behavior of the property
1, getter (value function)
class Parent{ constructor(name='Winnie'){ this.name=name; } get longName(){ return 'Liu'+this.name; } } let getterName=new Parent(); console.log(getterName.longName); // LiuWinnie
2, setter (stored-value function)
class Parent{ constructor(name='Winnie'){ this.name=name; } get longName(){ return 'Liu'+this.name; } set longName(value){ this.name=value; } } let setterName=new Parent(); setterName.longName='Honey'; console.log(setterName.longName); // LiuHoney
Fifth, the static method
Examples of the class corresponding to the prototype, all methods defined in the class, instance will be inherited.
But if coupled with the static keyword in front of a method, the method is not inherited instance, but directly invoked through the class, this method is called static methods.
1, the use of static keywords
class Parent{ static tell(){ console.log('hello'); } tell(){ console.log('world'); } } Parent.tell(); // hello
Code may also be seen that the above methods may be static and non-static method of the same name
2, static properties
class Parent { } Parent.lastName = 'Liu'; console.log(Parent.lastName); // Liu
The above code defines a static lastName property of Class Parent