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

JavaScript 的继承机制主要基于原型(prototype)实现,不同于传统面向对象语言的类继承。ES6 引入了 class 语法糖,让继承写法更清晰,但底层仍依赖原型链。
通过将子构造函数的 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'
缺点:所有子实例共享父类实例,若父类有引用类型属性,一个实例修改会影响其他实例。
在子构造函数中调用父构造函数,绑定 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'] —— 不互相影响
缺点:无法继承父类原型上的方法。
结合原型链和构造函数继承,既继承实例属性,又继承原型方法。
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;
};
这种方式兼顾了属性独立与方法复用,是传统模式下的推荐做法。
使用 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_如何实现继承机制的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号