8.4类

  • 类的两种定义方式 变量声明 和 表达式。
  • 函数声明可以提升,但类声明不可以提升。
  • 另一个跟函数声明不同的地方是,函数受函数作用域限制,而类受块作用域限制。

类声明中给类使用了名称,该名称不能在定义类的外部使用
image.png

constructor

方法名 constructor会告诉解释器在使用new 操作符创建类的实例时,应该调用这个函数。类实例化传入的参数会当做构造函数的参数。默认情况下,constructor 构造函数会默认返回this 对象 。 调用类构造函数必须使用 new 操作符,否则会报错。

image.png
静态成员 static ,常用于执行不特定实例的操作。 返回的this引用类自身。

  1. class Person {
  2. *getElement(){
  3. yield 'a';
  4. yield 'b';
  5. yield 'c';
  6. }
  7. }
  8. let e = new Person();
  9. let v = e.getElement()
  10. console.log(v.next().value); //a
  11. console.log(v.next().value); //b
  12. console.log(v.next().value); //c
  1. class Vehical{
  2. identifyP(id){
  3. console.log(id,this)
  4. }
  5. static indentifyC(id){
  6. console.log(id, this);
  7. }
  8. }
  9. class Car extends Vehical {};
  10. let myVehical = new Vehical();
  11. let myCar = new Car();
  12. myVehical.identifyP("AUTO")
  13. myCar.identifyP("BMW")
  14. Car.indentifyC("BMW1")

super

派生类的方法可以通过 super 关键字引用它们的原型

  • super 只能在派生类构造函数和静态方法中使用
  • 不能单独使用super 关键字。要么用它调用构造函数,要么用它引用静态方法
  • 调用super() 会调用父级构造函数,并将返回的实例赋给this
  • super() 的行为如同调用构造函数,如果需要给父类构造函数传参,则需要手动传入
  • 如果没有定义类构造函数,在实例化派生类时会调用 super() ,而且会传入所有传给派生类的参数。
  • 在类构造函数中,不能在super 之前引用 this
  • 如果在派生类中显式定义了构造函数,则一定要调用 super 或者返回一个对象。