JavaScript继承基于原型链,ES6的class为语法糖。1. 原型链继承通过子类prototype指向父类实例,实现方法共享,但引用属性共用有污染风险;2. 构造函数继承利用call调用父构造函数,实现属性独立,但无法继承原型方法;3. 组合继承结合两者优点,既通过call继承实例属性,又通过原型链继承方法,是传统方式中最推荐的;4. ES6 Class继承使用extends和super,语法清晰,语义明确,底层仍基于原型,是现代开发首选方案。

JavaScript 的继承机制主要基于原型(prototype)实现,不同于传统面向对象语言的类继承。ES6 引入了 class 语法糖,让继承写法更清晰,但底层仍依赖原型链。
1. 原型链继承(经典方式)
通过将子构造函数的 prototype 指向父构造函数的实例,实现属性和方法的继承。
function Parent() { this.name = 'parent';}Parent.prototype.getName = function() { return this.name;};function Child() { this.type = 'child';}// 继承父类原型Child.prototype = new Parent();const c = new Child();console.log(c.getName()); // 'parent'
缺点:所有子实例共享父类实例,若父类有引用类型属性,一个实例修改会影响其他实例。
2. 构造函数继承(借用构造函数)
在子构造函数中调用父构造函数,绑定 this,可传参。
立即学习“Java免费学习笔记(深入)”;
function Parent(name) { this.name = name; this.colors = ['red', 'blue'];}function Child(name, age) { Parent.call(this, name); // 继承并传参 this.age = age;}const c1 = new Child('Tom', 12);const c2 = new Child('Jerry', 10);c1.colors.push('green');console.log(c1.colors); // ['red', 'blue', 'green']console.log(c2.colors); // ['red', 'blue'] —— 不互相影响
缺点:无法继承父类原型上的方法。
3. 组合继承(最常用)
结合原型链和构造函数继承,既继承实例属性,又继承原型方法。
function Parent(name) { this.name = name; this.colors = ['red', 'blue'];}Parent.prototype.getName = function() { return this.name;};function Child(name, age) { Parent.call(this, name); // 继承实例属性 this.age = age;}Child.prototype = new Parent(); // 继承原型Child.prototype.constructor = Child; // 修正构造器指向Child.prototype.getAge = function() { return this.age;};
这种方式兼顾了属性独立与方法复用,是传统模式下的推荐做法。
4. ES6 Class 继承(现代写法)
使用 class 和 extends 关键字,语法更直观。
class Parent { constructor(name) { this.name = name; } getName() { return this.name; }}class Child extends Parent { constructor(name, age) { super(name); // 调用父类构造函数 this.age = age; } getAge() { return this.age; }}const c = new Child('Alice', 15);console.log(c.getName()); // 'Alice'console.log(c.getAge()); // 15
这是目前最推荐的方式,代码清晰,语义明确,底层仍是原型继承的封装。
基本上就这些。选择哪种方式取决于项目环境和需求,现代开发建议使用 class 语法。
以上就是javascript_如何实现继承机制的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1539965.html
微信扫一扫
支付宝扫一扫