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 的实例方法的原因。
相关推荐
AI即插即用7 小时前
即插即用系列(代码实践)专栏介绍
开发语言·人工智能·深度学习·计算机视觉
码农水水7 小时前
蚂蚁Java面试被问:混沌工程在分布式系统中的应用
java·linux·开发语言·面试·职场和发展·php
喵了meme7 小时前
c语言经验分享
c语言·开发语言
Knight_AL7 小时前
用 JOL 验证 synchronized 的锁升级过程(偏向锁 → 轻量级锁 → 重量级锁)
开发语言·jvm·c#
啊阿狸不会拉杆8 小时前
《数字图像处理》第 4 章 - 频域滤波
开发语言·python·数字信号处理·数字图像处理·频率域滤波
江沉晚呤时8 小时前
从零实现 C# 插件系统:轻松扩展应用功能
java·开发语言·microsoft·c#
Knight_AL8 小时前
Java 多态详解:概念、实现机制与实践应用
java·开发语言
Omigeq8 小时前
1.2.1 - 图搜索算法(以A*为例) - Python运动规划库教程(Python Motion Planning)
开发语言·python·机器人·图搜索算法
资深流水灯工程师8 小时前
基于Python的Qt开发之Pyside6 串口接收数据被分割的解决方案
开发语言·python·qt
没有bug.的程序员8 小时前
Java 并发容器深度剖析:ConcurrentHashMap 源码解析与性能优化
java·开发语言·性能优化·并发·源码解析·并发容器