Study Notes: ES6 class

Class basic grammar

JavaScript language conventional method is the constructor, and a new object is defined.

// define a constructor 
function Point (X, Y) {
     the this .x = X;
     the this .y = Y; 
} 

// add an instance constructor method on a prototype 
Point.prototype.toString = function () {
     return ' ( '+ the this .x +', '+ the this .y +') ' ; 
} 

// generate a new object 
var P = new new Point (. 1, 2);

 

The new wording just let the class object's prototype wording clearer, like object-oriented programming syntax only.

ES6 above code with "class" is rewritten, as follows:

// definition of class 
class Point { 
    constructor (X, Y) { // constructor, this representative example of an object 
        the this .x = X;
         the this .y = Y; 
    } 
    // methods (Examples will be inherited) class 
    toString () {
         return '(' + the this .x + ',' + the this .y + ')' 
    } 
} 

// generate a new object 
var P = new new Point (. 1, 2)

The method defined above class, are the properties described above in prototype.

Equivalent to the following ways:

Point.prototype = {
    toString () {}
}

 

 

constructor method

It is the default constructor for class and object instance is generated by the new command, the automatic calling method. There must be a class constructor methods, if not explicitly defined, an empty default constructor method will be added

The default constructor method returns an instance of an object (i.e. this), can specify another object returned.

Foo {class 
    constructor () { 
        return the Object.create ( null ); // modify the return value 
    } 
} 

new new Foo () the instanceof Foo
 // to false

 

Class constructor, NA new call error.

 

How to create an instance of the object class?

var point = new Point(2, 3);

 

Class Expression

// Class expression 
const MyClass class = Me { // Me Class available only inside the code refers to the current class, it may be omitted. 
    the getClassName () {
         return Me.Name; 
    } 
}

 

Private methods

slightly

 

this point

If the internal methods of the class containing this, which points to the default instance of the class.

 

Class inheritance

Inheritance can be achieved by keyword extends between Class.

class ColorPoint extends Point {}

 

super keyword shows the structure of the parent class for the new parent of this object
ES6 inheritance mechanism is to first create an object instance of this parent class (you must first call the super method), then use the constructor modify this subclass
constructor(...args) {
    super(...args);
}

 

Too long, behind all omitted ...

 

Reference article: http://jsrun.net/tutorial/SZKKp

 

Guess you like

Origin www.cnblogs.com/cathy1024/p/11200020.html