class类

class的实现

  • class对象内部的constructor及其方法,是作为构造器原型上的属性存在的,这也是我们说class是构造函数语法糖的原因,但是实际上class定义的函数,拥有特殊属性classConstructor,且不可枚举(这与es5不同),默认严格模式
  • 默认调用constructor函数,生成子类的this并返回,除非显式的定义在this(或者放在顶层)上否则所有属性都挂在原型上
  • 内部的this指向构造出来的实例,对于静态方法则指向class不被实例继承,可以被子类继承,通过super调用
  • new.target 实例通过new 或constructor 构造会返回构造函数名,子类的继承时会返回子类名(写出只有继承才能使用的类)
  • 没有变量提升,为了保证声明和继承的顺序
class Animal {
  constructor(name) {
    this.speed = 0;
    this.name = name;
  }
  run(speed) {
    this.speed = speed;
    alert(`${this.name} runs with speed ${this.speed}.`);
  }
  stop() {
    this.speed = 0;
    alert(`${this.name} stands still.`);
  }
}

let animal = new Animal("My animal");
image.png

Class的继承

  • 与ES5通过先创建子类的this对象,再将父类的方法通过call/apply添加到this上,最后返回子类的这种实现方式不同;
  • extend关键字继承时,期望通过调用父类(非继承)的constructor来实现this的创建,所以需要super来完成这个过程,因此,派生的 constructor 必须调用 super 才能执行其父类(非派生的)的 constructor,否则 this 指向的那个对象将不会被创建。并且我们会收到一个报错。继承后的实例查找过程类似原型查找
  • super作为函数只能在constructor中调用,作为对象调用时:普通方法中调用super指向父类的原型,赋值时等同this,内部的this指向子类构造出来的实例;静态方法里调用super则指向父类,内部的this指向子类(因为静态方法不能被实例继承)
  • 通过extend可以继承原生构造函数 ,而es5中使用.call()写法,无法继承原生构造函数,对于原生的属性方法会忽略传入的this值导致继承不完全
class Rabbit extends Animal {
  hide() {
    alert(`${this.name} hides!`);
  }
}

let rabbit = new Rabbit("White Rabbit");

rabbit.run(5); // White Rabbit runs with speed 5.
rabbit.hide(); // White Rabbit hides!
// 继承关系
Object.setPrototypeOf = function (obj, proto) {
  obj.__proto__ = proto;
  return obj;
}
// 父类指向子类
class A {
}

class B extends A {
}

B.__proto__ === A // true
B.prototype.__proto__ === A.prototype // true
// 没有继承关系
class A {
}

A.__proto__ === Function.prototype // true
A.prototype.__proto__ === Object.prototype // true

// 实例的原型的原型指向父类的原型
var p1 = new Point(2, 3);
var p2 = new ColorPoint(2, 3, 'red');

Object.getPrototypeOf(ColorPoint) === Point  // true
p2.__proto__ === p1.__proto__ // false
p2.__proto__.__proto__ === p1.__proto__ // true
image.png

通过super调用使用了一个新的属性 [[HomeObject]] 他记住了对象的属性,这个属性必须要当做对象的方法才能调用

你可能感兴趣的:(class类)