Several attributes and methods of class in ES6 and the corresponding Es5 writing method

Time:2021-12-22

summary

In ES6, class can be regarded as a syntax sugar, which makes the writing of object prototype clearer and more like the syntax of object-oriented programming.

This paper introduces several properties and methods of class and the corresponding Es5 writing method

To read this article, you need to master the knowledge of prototype. It is recommended to read itHelp you thoroughly understand the prototype in JS__ proto__ And constructor (illustration)

Static properties and static methods

Static attribute: the attribute of the class itself, that is, the attribute directly defined inside the class (class. Propname), which does not need to be instantiated

class Example {
  static num = 2; // ES7
  static sum(a, b) {
    console.log(a + b);
  }
}

amount to

function Example() {}
Example.num = 2;
Example.sum = function sum(a, b) {
  console.log(a + b);
};

use

console.log(Example.num);
Example.sum(1, 2);

Common attributes and prototype methods

class Example {
  //Prototype method
  sum(a, b) {
    console.log(a + b);
  }
}
Example. prototype. num = 2;  //  Public attribute

amount to

function Example() {}
Example.prototype.sum = function sum(a, b) {
  console.log(a + b);
};
Example.prototype.num = 2;

use

let exam = new Example();
console.log(exam.num);
exam.sum(1, 2); // 3

Instance properties and instance methods

class Example {
  num = 2;
  sum = (a, b) => {
    console.log(a + b);
  }
}

amount to

class Example {
  constructor() {
    this.num = 2;
    this.sum = (a, b) => {
      console.log(a + b);
    }
  }
}

amount to

function Example() {
  this.num = 2;
  this.sum = function (a, b) {
    console.log(a + b);
  }
}

use

let exam = new Example();
console.log(exam.num);
exam.sum(1, 2); // 3