Class类

Class类

  • 之前建立构造函数函数

    function Person(name){
    this.name = name
    }
    Person.prototype.say = function(){
    console.log( `hi, my name is ${this.name}`);
    }
  • ES6 的类,彻底能够看做构造函数的另外一种写法this

    class Point {
    // ...
    }
    
    typeof Point // "function"
    Point === Point.prototype.constructor // true
    class Point {
    constructor() {
      // ...
    }
    
    toString() {
      // ...
    }
    
    toValue() {
      // ...
    }
    }
    
    // 等同于
    
    Point.prototype = {
    constructor() {},
    toString() {},
    toValue() {},
    };
  • constructor 方法

一个类必须有constructor()方法,若是没有显式定义,一个空的constructor()方法会被默认添加prototype

constructor()方法默认返回实例对象(即this),彻底能够指定返回另一个对象code

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

new Foo() instanceof Foo
// false
  • 实例方法,静态方法 static对象

    class Person{ //定义一个person类型
    constructor(name){ //构造函数
      this.name = name  //当前person类型的实例对象
    }
    say(){
      console.log( `hi, my name is ${this.name}`);
    }
    static create (name){ //静态方法内部this不会指向某个实例对象,而是当前的类型
      return new Person(name)
    }
    }
    const p = new Person("mcgee")
    p.say()
    
    const jack = Person.create("jack")
    jack.say()
  • 类的继承 extends

子类必须在constructor方法中调用super方法,不然新建实例时会报错。这是由于子类本身的this对象,必须先经过父类的构造函数完成塑造,获得与父类一样的实例属性和方法,而后再对其进行加工,加上子类本身的实例属性和方法。若是不调用super方法,子类就得不到this对象继承

class Student extends Person{
  constructor(name,number)
  {
    super(name) //super对象,始终指向父类,调用它就是调用父类的构造函数
    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()
  • 类不存在变量提高
new Foo(); // ReferenceError
class Foo {}
  • 父类静态方法也会被子类继承
class A {
  static hello() {
    console.log('hello world');
  }
}

class B extends A {
}

B.hello()  // hello world