Class Class

  • Create the constructor previously

    function Person(name){
    this.name = name
    }
    Person.prototype.say = function(){
    console.log( `hi, my name is ${this.name}`);
    }
  • The ES6 class can be thought of as just another way of writing a constructor

    class Point {
    // ...
    }
    
    typeof Point // "function"
    Point === Point.prototype.constructor // true
    class Point { constructor() { // ... } toString() { // ... } toValue() { // ... }} / / equivalent Point. The prototype = {constructor () {}, the toString () {}, toValue () {},};
  • The constructor method

A class must have a constructor() method. If not explicitly defined, an empty constructor() method is added by default

The constructor() method returns an instance object by default (that is, this), but it is entirely possible to specify that another object should be returned

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

new Foo() instanceof Foo
// false
  • Instance method, static method

    Class Person{// define a Person type constructor(constructor(name){// constructor this.name = name // instance of the current Person type} say(){console.log(' hi, '); my name is ${this.name}`); } const p = new Person(" McGee ") p.ay ();} const p = new Person(" McGee ") p.ay ();} const p = new Person(" McGee ") p.ay ();  const jack = Person.create("jack") jack.say()
  • Class extends

The subclass must call the super method in the constructor method, otherwise the new instance will get an error. This is because the subclass’s own this object must first be molded through the constructor of the superclass to obtain the same instance properties and methods as the superclass’s, and then it must be processed to add the subclass’s own instance properties and methods. If you do not call the super method, the subclass will not get this object

Class Student extends Person{constructor(name,number) {super(name) {super(name); To call it is to call the constructor of the parent class this.number = number} hello(){super.say() console.log(' My school number is ${this.number} '); } } const ex = new Student("mcgee",123) console.log(ex.name); ex.hello()
  • Class does not have variable promotion
new Foo(); // ReferenceError
class Foo {}
  • Superclass static methods are also inherited by subclasses
class A {
  static hello() {
    console.log('hello world');
  }
}

class B extends A {
}

B.hello()  // hello world