JavaScript继承基于原型链,对象通过[[Prototype]]链接向上查找属性;ES6 class为语法糖,底层仍为原型继承。

JavaScript 的继承机制不同于传统的面向对象语言,它基于原型链(Prototype Chain)实现。虽然 ES6 引入了 class 语法糖,让代码看起来更接近类式语言,但底层依然是原型继承。理解原型链是掌握 JavaScript 面向对象编程的关键。
在 JavaScript 中,每个对象都有一个内部属性 [[Prototype]],指向其原型对象。这个链接构成了“原型链”:
例如:
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
return "Hello, I'm " + this.name;
};
const alice = new Person("Alice");
console.log(alice.greet()); // "Hello, I'm Alice"
// alice → Person.prototype → Object.prototype → null
JavaScript 提供多种方式模拟继承,以下是常见模式:
立即学习“Java免费学习笔记(深入)”;
1. 原型链继承将子类的 prototype 指向父类的实例:
function Child() {}
Child.prototype = new Parent();
缺点:所有实例共享引用类型属性,无法向父类传参。
2. 构造函数继承(借用构造函数)在子类构造中调用父类构造函数:
function Child(name) {
Parent.call(this, name);
}
优点:可传参,避免引用共享。缺点:无法继承原型上的方法。
3. 组合继承(常用)结合前两者,最通用的模式:
function Child(name, age) {
Parent.call(this, name); // 继承实例属性
this.age = age;
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child; // 修正构造器
既继承了实例属性,也继承了原型方法。
4. ES6 Class 继承使用 class 和 extends 语法,更清晰简洁:
class Person {
constructor(name) {
this.name = name;
}
greet() {
return `Hello, I'm ${this.name}`;
}
}
class Student extends Person {
constructor(name, grade) {
super(name);
this.grade = grade;
}
study() {
return `${this.name} is studying.`;
}
}
底层仍是原型链,但语义更强,推荐在现代项目中使用。
基于原型机制,可以实现常见设计模式:
工厂模式封装对象创建过程,返回带有方法的对象:
function createUser(name) {
return {
name,
greet() { return `Hi, I'm ${this.name}`; }
};
}
确保一个类仅有一个实例:
class Logger {
constructor() {
if (Logger.instance) return Logger.instance;
Logger.instance = this;
this.logs = [];
}
log(msg) { this.logs.push(msg); }
}
以上就是JavaScript原型链_继承机制与类设计模式的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号