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 的实例方法的原因。
相关推荐
qetfw3 分钟前
Bash 基础:脚本执行、引号与命令替换验证
linux·开发语言·chrome·bash
杜 硕22 分钟前
从零开始的C++生活——第四讲
开发语言·c++·生活
云和数据.ChenGuang28 分钟前
Python 集合(set)常用函数详解与实战案例
开发语言·python·深度学习·langchain
隔窗听雨眠40 分钟前
从PHP2Shell回望:PHP内核漏洞的二十年演进与AI时代的攻防转折
开发语言·人工智能·php
lisw0543 分钟前
分岔论揭示演化突变密码
开发语言·算法·数学建模
hunteritself44 分钟前
AI 挖出 PHP「致命漏洞」!欧洲政府连夜关站,日本首相紧急喊话
开发语言·人工智能·php
努力实干1 小时前
Qt/C++ 模块化设计与工程组织
开发语言·c++·qt
阿里嘎多学长1 小时前
2026-10-23 GitHub 热点项目精选
开发语言·程序员·github·代码托管
Lhan.zzZ1 小时前
Qt:动态库模块框架设计
开发语言·c++·qt
quantdash_cc1 小时前
如何从多只股票的历史行情构建收益率矩阵?Python 与 QuantDash 实战教程
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash