Javascript 中的继承

Javascript 中的继承基于原型链。

js 复制代码
// 创建一个父类
class Parent {
  static staticMethod() {
    console.log('This is a static method on Parent class')
  }
  constructor(name) {
    this.name = name
  }
  greet() {
    console.log('Hello, my name is ' + this.name)
  }
}
// 创建一个子类
class Child extends Parent {
  constructor(name, age) {
    // 调用父类构造函数
    super(name)
    this.age = age
  }
  // 为子类添加方法
  introduce() {
    console.log('I am ' + this.name + ' and I am ' + this.age + ' years old.')
  }
}

// 使用继承的类
const childInstance = new Child('Alice', 10)
childInstance.greet() // 输出: Hello, my name is Alice
childInstance.introduce() // 输出: I am Alice and I am 10 years old.
Child.staticMethod() // 输出: This is a static method on Parent class

Object.getPrototypeOf(Child) === Parent // true
Object.getPrototypeOf(childInstance) === Child.prototype // true
Object.getPrototypeOf(Child.prototype) === Parent.prototype // true

当我们访问 Child.staticMethod() 时,JavaScript 引擎会按照以下顺序查找方法:

  1. 在 Child 类本身查找 staticMethod 方法。
  2. 如果没有找到,则在 Child 的原型(即 Parent 类)上查找 staticMethod 方法。
  3. 找到后执行它。
    这就是为什么 Child 能调用 Parent 的静态方法的原因。

当我们访问 childInstance.greet() 时,JavaScript 引擎会按照以下顺序查找方法:

  1. 在 childInstance 对象本身查找 greet 方法。
  2. 如果没有找到,则在 childInstance 的原型(即 Child.prototype)上查找 greet 方法。
  3. 如果仍然没有找到,则在 Child.prototype 的原型(即 Parent.prototype)上查找 greet 方法。
  4. 找到后执行它。
    这就是为什么 childInstance 能调用 Parent 的实例方法的原因。
相关推荐
凤山老林34 分钟前
04-Java JDK, JRE和JVM
java·开发语言·jvm
灵感__idea6 小时前
Hello 算法:贪心的世界
前端·javascript·算法
小成202303202657 小时前
Linux高级02
linux·开发语言
知行合一。。。7 小时前
Python--04--数据容器(总结)
开发语言·python
咸鱼2.07 小时前
【java入门到放弃】需要背诵
java·开发语言
ZK_H7 小时前
嵌入式c语言——关键字其6
c语言·开发语言·计算机网络·面试·职场和发展
A.A呐7 小时前
【C++第二十九章】IO流
开发语言·c++
椰猫子7 小时前
Java:异常(exception)
java·开发语言
lifewange7 小时前
pytest-类中测试方法、多文件批量执行
开发语言·python·pytest
cmpxr_8 小时前
【C】原码和补码以及环形坐标取模算法
c语言·开发语言·算法