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 的实例方法的原因。
相关推荐
寻星探路3 小时前
【深度长文】万字攻克网络原理:从 HTTP 报文解构到 HTTPS 终极加密逻辑
java·开发语言·网络·python·http·ai·https
lly2024064 小时前
Bootstrap 警告框
开发语言
2601_949146535 小时前
C语言语音通知接口接入教程:如何使用C语言直接调用语音预警API
c语言·开发语言
曹牧5 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
KYGALYX5 小时前
服务异步通信
开发语言·后端·微服务·ruby
zmzb01035 小时前
C++课后习题训练记录Day98
开发语言·c++
猫头虎6 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
Moment6 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
YUJIANYUE6 小时前
PHP纹路验证码
开发语言·php
爱敲代码的小鱼6 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax