ES5继承靠构造函数借用和原型链组合实现,ES6用class/extends/super语法糖并自动建立完整原型链与静态继承。

ES5没有class关键字,实现继承主要靠组合使用构造函数借用(call/apply)和原型链继承。核心思路是:子类实例先拥有父类的实例属性,再让子类原型指向父类原型的副本,从而共享方法。
常见写法(寄生组合式继承,最推荐):
function Parent(name) {
this.name = name;
}
Parent.prototype.say = function() {
console.log('Hello from ' + this.name);
};
function Child(name, age) {
Parent.call(this, name); // 借用构造函数,继承实例属性
this.age = age;
}
// 关键:用Object.create(Parent.prototype)避免调用Parent构造函数
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child; // 修复constructor指向
Child.prototype.play = function() {
console.log(this.name + ' is playing');
};
⚠️ 注意点:
Child.prototype = Parent.prototype,否则修改子类原型会影响父类constructor,否则new Child().__proto__.constructor会指向Parent
Parent.staticMethod = () => {}),需额外拷贝ES6引入class语法糖,但本质仍是基于原型的继承。使用extends声明继承关系,子类构造函数中必须调用super()——它负责初始化this并连接原型链。
立即学习“Java免费学习笔记(深入)”;
class Parent {
constructor(name) {
this.name = name;
}
say() {
console.log('Hello from ' + this.name);
}
static create() {
return new Parent('default');
}
}
class Child extends Parent {
constructor(name, age) {
super(name); // 必须!相当于Parent.call(this, name)
this.age = age;
}
play() {
console.log(this.name + ' is playing');
}
// 静态方法也能被继承
static build() {
return new Child('test', 10);
}
}
✅ 优势明显:
Child.__proto__ === Parent(静态继承),Child.prototype.__proto__ === Parent.prototype(实例方法继承)super()会直接报错,强制规范流程表面上是语法糖,底层机制有实质性区别:
Child.prototype = ...;ES6在extends时就自动设置好Child.prototype.__proto__和Child.__proto__
this在子构造函数里已存在;ES6中子类构造函数里,this在super()执行前是未初始化的,直接访问会报ReferenceError
Child.staticMethod继承Parent.staticMethod;ES5需手动赋值Child.staticMethod = Parent.staticMethod
get/set、static、private #field等特性,ES5模拟成本高且不统一新项目一律用ES6 class继承。ES5写法仅需了解,用于阅读老代码或兼容极旧环境(如IE)。
遇到报错Must call super constructor in derived class before accessing 'this'?说明忘了在子类constructor第一行写super()。
想在子类中调用父类同名方法?用super.methodName(),这是ES6新增的语法,ES5得写Parent.prototype.methodName.call(this)。
基本上就这些。理解原型链本质,再看class语法,就不会被“语法糖”三个字带偏了。
以上就是JavaScript中如何实现继承_ES5和ES6继承方式对比的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号