machao07 / interview-questions

前端技术栈相关面试知识点( Vue、React、Typescript、JavaScript...),喜欢请点start

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ES6中的class

machao07 opened this issue · comments

class

  • class是一个语法糖,其底层还是通过 构造函数 去创建

  • 类相当于实例的原型,所有在类中定义的方法,都会被实例继承

静态方法

加上 static 关键字,该方法不会被实例继承,而是直接通过类来调用

class A {
    static classMethod() {
        return 'hello'
    }
}
A.classMethod()

console.log(A.classMethod()) // 'hello'

const a = new A()
a.classMethod()
// TypeError: a.classMethod is not a function
静态方法包含this关键字,这个this指的是类,而不是实例
  • 静态方法可以与非静态方法重名
class A {
    static classMethod() {
      this.baz()
    }
    static baz() {
      console.log('hello')
    }
    baz() {
      console.log('world')
    }
}
A.classMethod()  // hello
父类的静态方法,可以被子类继承
class A {
    static classMethod() {
        console.log('hello');
    }
}

class B extends A {}

B.classMethod() // 'hello'

静态属性

  • 指的是 Class 本身的属性,而不是定义在实例对象(this)上的属性
  • 写法是在实例属性的前面,加上static关键字
class MyClass {
  static myStaticProp = 42;

  constructor() {
    console.log(MyClass.myStaticProp); // 42
  }
}

继承

  • 通过 extends关键字实现继承
  • 不管有没有显式定义,任何一个子类都有 constructor方法
父类的静态方法,也会被子类继承
class A {
  static hello() {
    console.log('hello world');
  }
}

class B extends A {
}

B.hello()  // hello world

super

既可以当作函数使用,也可以当作对象使用

函数调用

在super()执行时,它指向的是子类B的构造函数,而不是父类A的构造函数

class A {
  constructor() {
    // new.target 指向正在执行的函数
    console.log(new.target.name);
  }
}

class B extends A {
  constructor() {
    super();
  }
}

new A() // A
new B() // B  B {}

image

对象调用

普通函数中调用

  • super 指向父类的原型对象 A.prototype
  • super.p() 相当于 A.prototype.p()
class A {
  p() {
    return 2;
  }
}

class B extends A {
  constructor() {
    super();
    console.log(super.p()); // 2
  }
}

let b = new B();

静态方法中调用

  • super 指向父类,而不是父类的原型对象
class Parent {
  static myMethod(msg) {
    console.log('static', msg);
  }
 
  myMethod(msg) {
    console.log('instance', msg)
  }
}

class Child extends Parent {
  static myMethod(msg) {
    super.myMethod(msg)
  }

  myMethod(msg) {
    super.myMethod(msg)
  }
}

Child.myMethod(1) // static 1

const child = new Child()
child.myMethod(2) // instance 2