javascript中的类与继承是如何实现的【教程】

技术百科 幻影之瞳 发布时间:2026-01-27 浏览:
JavaScript的类是基于原型的语法糖,class声明本质是函数加prototype操作,实例属性须在constructor中用this显式初始化,继承必须正确调用super()以维护原型链。

JavaScript 的类和继承不是传统面向对象语言那种“编译时确定的类型系统”,而是基于原型(prototype)的语法糖——class 关键字本身不创建新机制,只是让原型链操作更可读、更结构化。

class 声明本质是函数 + prototype 操作

class 声明会被 JavaScript 引擎转为一个具有 constructor 属性的函数,并自动设置其 prototype。你不能在 class 内部用 = 直接给实例赋值成员变量(像 Python 那样),所有实例属性必须在 constructor 中通过 this.xxx = 显式初始化。

  • class Person {} 等价于 function Person() {},且 Person.prototype 自动存在
  • 类方法(如 sayHello())被添加到 Person.prototype 上,不是每个实例都拷贝一份
  • 类中不允许写 var name = 'xxx' 这样的语句;静态属性需用 Person.version = 1static version = 1(ES2025+)

extends 和 super 的调用顺序很关键

子类构造函数中,必须在访问 this 前调用 super()——否则会抛出 ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor。这是因为子类实例的内部槽([[Prototype]])依赖 super() 来正确链接到父类原型。

  • super() 必须出现在 constructor 第一行(或至少在任何 this 访问之前)
  • super.xxx 可用于访问父类原型上的方法,但不能在 super() 调用前使用
  • 如果子类没写 constructor,引擎会自动注入 constructor(...args) { super(...args); }

继承链断裂常见于手动改写 prototype

直接赋值 Child.prototype = Parent.prototypeChild.prototype = new Parent() 是危险操

作:前者会让子类修改影响父类,后者可能触发父类构造函数副作用(比如发请求、改全局状态),且无法正确设置 constructor 指针和 __proto__ 链。

  • 正确做法始终是用 extends,它底层调用 Object.setPrototypeOf(Child.prototype, Parent.prototype)
  • 若必须手写继承(如兼容老环境),应使用 Object.create(Parent.prototype) 并重设 constructor
  • instanceof 判断依赖原型链,手动改错 prototype 会导致 new Child() instanceof Parent === false

真正容易被忽略的是:类字段声明(name = 'x')属于 ES2025 提案,Babel 默认不编译它为可兼容代码;而 static 字段、私有字段(#age)的运行时行为与普通属性完全不同——它们不走 prototype,也不参与 for...in 遍历。别假设“写了 class 就等于 Java 那套”。


# 的是  # 也不  # 能在  # 写了  # 出现在  # python  # 但不  # 会让  # 你不  # 对象  # javascript  # java  # class  # 指针  # 子类  # 构造函数  # access  # Static  # function  # var  # this  # 成员变量  # 继承  # Object  # 遍历  # for  # 父类  # 面向对象  # constructor  # prototype 


相关栏目: <?muma $count = M('archives')->where(['typeid'=>$field['id']])->count(); ?> 【 AI推广<?muma echo $count; ?> 】 <?muma $count = M('archives')->where(['typeid'=>$field['id']])->count(); ?> 【 SEO优化<?muma echo $count; ?> 】 <?muma $count = M('archives')->where(['typeid'=>$field['id']])->count(); ?> 【 技术百科<?muma echo $count; ?> 】 <?muma $count = M('archives')->where(['typeid'=>$field['id']])->count(); ?> 【 谷歌推广<?muma echo $count; ?> 】 <?muma $count = M('archives')->where(['typeid'=>$field['id']])->count(); ?> 【 百度推广<?muma echo $count; ?> 】 <?muma $count = M('archives')->where(['typeid'=>$field['id']])->count(); ?> 【 网络营销<?muma echo $count; ?> 】 <?muma $count = M('archives')->where(['typeid'=>$field['id']])->count(); ?> 【 案例网站<?muma echo $count; ?> 】 <?muma $count = M('archives')->where(['typeid'=>$field['id']])->count(); ?> 【 精选文章<?muma echo $count; ?>

相关推荐

在线咨询

点击这里给我发消息QQ客服

在线咨询

免费通话

24h咨询:4006964355


如您有问题,可以咨询我们的24H咨询电话!

免费通话

微信扫一扫

微信联系
返回顶部