Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Abstract

ES6, short for ECMAScript 6.0, is the next generation standard of the JavaScript language. The relationship between ECMAScript and JavaScript is that the former is a specification of the latter and the latter is an implementation of the former.

The basic syntax of Class

ES6 written before
function Point(x, y) {
    this.x = x
    this.y = y
}

Point.prototype.toString() {
    return '(' + this.x + ', ' + this.y + ') '
}

var p = new Point(1.2)
Copy the code
ES6 writing
class Point {
    constructor(x, y) {
        this.x = x
        this.y = y
    }
    
    toString() {
        return '(' + this.x + ', ' + this.y + ') '}}Copy the code

Constructor (); this stands for instance object

All methods of a class are defined on the prototype property of the class

class Point {
    constructor() {}
    
    toString() {}
    
    toValue(){}}/ / is equivalent to
Point.prototype = {
    constructor() {},
    toString() {},
    toValue(){}}Copy the code

The constructor method

Constructor () is the class’s default method, which is automatically called when an object instance is generated. A class must have a constructor() method; if it is not explicitly defined, an empty constructor() method is added by default.

class Point {}

/ / is equivalent to
class Point {
  constructor(){}}Copy the code

The class must be called with new or an error will be reported. Normal constructors can be executed without new.

class Foo {
  constructor() {
    return Object.create(null);
  }
}

Foo()
Copy the code

Attribute expression

The property name of the class, which can take an expression.

let methodName = 'getArea';

class Square {
  constructor() {}

  [methodName]() {}
}
Copy the code

In the code above, the Square class method name, getArea, is derived from the expression.

Pay attention to the point

  • There is no variable promotion
new Foo()
class Foo {}
Copy the code

  • This point

Class methods that contain this inside point to instances of the class by default. You must be careful, however, that you may get an error if you use this method alone.

class Logger {
  printName(name = 'there') {
    this.print(`Hello ${name}`)}print(text) {
    console.log(text)
  }
}

const logger = new Logger()
const { printName } = logger
printName()
Copy the code