当前位置: 首页 > news >正文

如何实现一个构造函数继承另一个构造函数的属性和方法?给出ES5和ES6两种方式

在 JavaScript 中,构造函数继承可以通过 原型链构造函数调用 实现。以下是 ES5ES6 的实现方式:


ES5 实现方式

关键步骤
  1. 继承实例属性:在子构造函数中调用父构造函数的 call/apply,绑定 this
  2. 继承原型方法:将子构造函数的原型设置为父构造函数的实例,形成原型链。
  3. 修复 constructor:修正子构造函数原型的 constructor 指向自身。
代码实现
// 父构造函数
function Parent(name) {this.name = name; // 实例属性
}
Parent.prototype.sayName = function() { // 原型方法console.log("Parent name:", this.name);
};// 子构造函数
function Child(name, age) {// 1. 继承父构造函数的实例属性Parent.call(this, name); // 绑定 this,传递参数this.age = age;
}// 2. 继承父构造函数的原型方法
Child.prototype = Object.create(Parent.prototype); // 建立原型链// 3. 修复 constructor 指向
Child.prototype.constructor = Child;// 子类新增原型方法
Child.prototype.sayAge = function() {console.log("Child age:", this.age);
};// 测试
const child = new Child("Alice", 10);
child.sayName(); // Parent name: Alice
child.sayAge();  // Child age: 10
关键点
  • Parent.call(this):确保子类实例继承父类的实例属性。
  • Object.create(Parent.prototype):避免直接调用 new Parent()(可能触发父类副作用),仅继承原型方法。
  • 修复 constructor:防止原型链混乱(否则 child.constructor 会指向 Parent)。

ES6 实现方式

ES6 通过 classextends 简化继承,底层依然基于原型链。

代码实现
// 父类
class Parent {constructor(name) {this.name = name; // 实例属性}sayName() { // 原型方法console.log("Parent name:", this.name);}
}// 子类继承父类
class Child extends Parent {constructor(name, age) {super(name); // 必须调用 super(),继承父类实例属性this.age = age;}sayAge() { // 子类原型方法console.log("Child age:", this.age);}
}// 测试
const child = new Child("Bob", 12);
child.sayName(); // Parent name: Bob
child.sayAge();  // Child age: 12
关键点
  • extends:建立原型链,自动继承父类原型方法。
  • super():必须优先调用,相当于 Parent.call(this),负责初始化父类实例属性。
  • 无需手动维护原型链和 constructor:语法糖自动处理。

对比总结

特性ES5ES6
语法手动操作原型链和构造函数调用使用 classextends 语法糖
实例属性继承通过 Parent.call(this)通过 super()
原型方法继承手动设置 Child.prototype = Object.create()自动通过 extends 实现
constructor 修复需手动修正 Child.prototype.constructor自动维护
静态方法继承需手动处理(如 Child.__proto__ = Parent自动继承

注意事项

  1. ES6 的 super
    • 必须在子类 constructor优先调用,否则报错。
    • super 在方法中可调用父类原型方法(如 super.sayName())。
  2. 静态方法继承
    • ES5 中需手动设置 Child.__proto__ = Parent
    • ES6 中通过 extends 自动继承父类的静态方法。

通过 ES5 显式原型链操作ES6 的 class 语法,均可实现构造函数继承。ES6 的语法更简洁且更接近传统面向对象语言,推荐优先使用。

相关文章:

  • 软件研发过程中的技术债
  • (Matlab)自动驾驶仿真 设计驾驶场景、配置传感器并生成合成 数据
  • #Liunx内存管理# 页面分配器是按照什么方向来扫描zone的?
  • 第一期第10讲
  • ShellScript脚本编程
  • C语言 - 深拷贝与浅拷贝详解
  • 【扩散模型连载 · 第 2 期】逆向扩散建模与神经网络的角色
  • Object.create(null)`和`{}`创建的对象有什么区别?
  • git提交规范
  • Linux的应用领域,测试与Linux,Linux的介绍,VirtualBox和Ubuntu的安装,VMware的安装和打开虚拟机CentOS
  • 密码学(二)流密码
  • Delphi HMAC算法
  • Spring常用注解
  • 大模型在轮状病毒肠炎预测及临床方案制定中的应用研究
  • 工厂能耗系统智能化解决方案 —— 安科瑞企业能源管控平台
  • AF3 create_alignment_db_sharded脚本create_shard函数解读
  • mysql删除表后重建表报错Tablespace exists
  • Grafana安装
  • 云服务器X86计算和Arm计算架构有什么区别?
  • 莒县第六实验小学:举行“阅读世界 丰盈自我”淘书会
  • fusion做电影网站卡死/全国疫情高中低风险区一览表
  • 昆明网站建设兼职/网站推广的软件
  • 百度网站优化/网页制作图片
  • 做网站商业欺骗赔多少/百度云网盘搜索引擎
  • 网站建设收费/中国网站排名查询
  • 佛山微信网站推广多少钱/网站推广软件费用是多少