1, ES6 provided closer to the traditional language of the writing, we introduce Class (Class) concept as an object template. By class
keyword, you can define classes.
2、
//定义类 class Point { constructor(x, y) { this.x = x; this.y = y; } toString() { return '(' + this.x + ', ' + this.y + ')'; } }
The above code defines a "class", there can be seen a constructor
method, which is the constructor, the this
keyword represents the object instance. That is, the constructor of ES5 Point
, ES6 corresponding to the Point
class constructor.
3, define methods "class" of the time, does not require preceded by function
the keyword directly into the function definition went on it. Further, the method does not require between commas, plus error.
4, the constructor prototype
property, continues to exist above the "class" of for ES6. In fact, all methods defined in the class are the class prototype
attributes above.
class Point { constructor(){ // ... } toString(){ // ... } toValue(){ // ... } } // 等同于 Point.prototype = { toString(){}, toValue(){} };
5, Object.assign
the method can easily add more methods to the class.
class Point { constructor(){ // ... } } Object.assign(Point.prototype, { toString(){}, toValue(){} });
6, the interior of all defined class methods are not enumerable (non-enumerable). This behavior is inconsistent with ES5.
7, the attribute name of the class, you can use an expression.
let methodName = "getArea"; class Square{ constructor(length) { // ... } [methodName]() { // ... } }
In the above code, Square
the method name of the class getArea
, is obtained from the expression.
8, constructor
is the default class method, by new
generating a command object instance, the method is automatically invoked. There must be a class constructor
method, if no explicit definition, an empty constructor
method will be added by default. constructor
The method returns an instance of a default object (i.e. this
), you can specify another object returned.
9, the class constructor is not used new
is not invoked, being given.
10, by way of example may be a __proto__
method of adding to the Class property.
var p1 = new Point(2,3); var p2 = new Point(3,2); p1.__proto__.printName = function () { return 'Oops' }; p1.printName() // "Oops" p2.printName() // "Oops" var p3 = new Point(4,2); p3.printName() // "Oops"
11, using examples of __proto__
properties overwrite prototype must be very careful not recommended, because it will change the original definition of the Class, affecting all instances.
12, Class variable lift (hoist) does not exist.