Skip to content

class 继承

提示

https://zh.javascript.info/class-inheritance#zong-jie

  1. 想要扩展一个类:class Child extends Parent:

    • 这意味着 Child.prototype.proto 将是 Parent.prototype,所以方法会被继承。
  2. 重写一个 constructor:

    • 在使用 this 之前,我们必须在 Child 的 constructor 中将父 constructor 调用为 super()。
  3. 重写一个方法:

    • 我们可以在一个 Child 方法中使用 super.method() 来调用 Parent 方法。
  4. 内部:

    • 方法在内部的 [[HomeObject]] 属性中记住了它们的类/对象。这就是 super 如何解析父方法的。
    • 因此,将一个带有 super 的方法从一个对象复制到另一个对象是不安全的。

补充:

  • 箭头函数没有自己的 this 或 super,所以它们能融入到就近的上下文中,像透明似的。

类继承是一个类扩展另一个类的一种方式。

“extends” 关键字

js
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!
js
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')

在内部,关键字 extends 使用了很好的旧的原型机制进行工作。它将 Rabbit.prototype.[[Prototype]] 设置为 Animal.prototype。所以,如果在 Rabbit.prototype 中找不到一个方法,JavaScript 就会从 Animal.prototype 中获取该方法。

animal-rabbit-extends

例如,要查找 rabbit.run 方法,JavaScript 引擎会进行如下检查(如图所示从下到上):

  1. 查找对象 rabbit(没有 run)。
  2. 查找它的原型,即 Rabbit.prototype(有 hide,但没有 run)。
  3. 查找它的原型,即(由于 extendsAnimal.prototype,在这儿找到了 run 方法。

extends 后允许任意表达式

类语法不仅允许指定一个类,在 extends 后可以指定任意表达式。

例如,一个生成父类的函数调用:

js
function f(phrase) {
  return class {
    sayHi() {
      alert(phrase)
    }
  }
}

class User extends f('Hello') {}

new User().sayHi() // Hello

重写方法

重写 constructor

基于 MIT 许可发布