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 的实例方法的原因。
相关推荐
盐焗鹌鹑蛋2 分钟前
【C++】继承
开发语言·c++
HUMHSX34 分钟前
Vue 组件通信核心知识点梳理
javascript·vue.js·ecmascript
栈溢出了37 分钟前
Java Lambda 表达式笔记
java·开发语言·intellij-idea
zhixingheyi_tian1 小时前
一份GC日志的解读
java·开发语言
czhaii1 小时前
串口1中断收发-C语言-MODBUS协议
c语言·开发语言
风止何安啊1 小时前
🚦 前端并发请求 “交通管制”:别让你的接口堵成早高峰
前端·javascript·面试
熊猫钓鱼>_>1 小时前
2026 前端的三场底层革命:当 Vue、React Native 和 Three.js 同时去掉中间层
前端·javascript·vue.js·react native·架构·webgl·three.js
名字还没想好☜1 小时前
React useEffect 依赖数组踩坑:闭包陷阱与清理函数
前端·javascript·react.js·react·useeffect
apihz1 小时前
随机驾考题目(C 照科一 / 科四 2000+ 题)免费API调用教程
android·java·c语言·开发语言·网络协议·tcp/ip
matlab代码2 小时前
基于matlab人脸疲劳驾驶检测系统(可使用其它人脸视频)【源码39期】
开发语言·matlab·人脸疲劳检测