js实现extends
实现 JavaScript 的 extends 功能
JavaScript 中实现继承可以通过原型链和 class 语法来实现 extends 的功能。以下是两种常见的方法:

使用 ES6 的 class 和 extends
ES6 引入了 class 和 extends 关键字,使得继承更加直观和易于理解。

class Parent {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, ${this.name}!`);
}
}
class Child extends Parent {
constructor(name, age) {
super(name); // 调用父类的 constructor
this.age = age;
}
greet() {
super.greet(); // 调用父类的 greet 方法
console.log(`I am ${this.age} years old.`);
}
}
const child = new Child('Alice', 10);
child.greet();
// 输出:
// Hello, Alice!
// I am 10 years old.
使用原型链实现继承(ES5 及之前)
在 ES5 及之前的版本中,可以通过原型链手动实现继承。
function Parent(name) {
this.name = name;
}
Parent.prototype.greet = function() {
console.log(`Hello, ${this.name}!`);
};
function Child(name, age) {
Parent.call(this, name); // 调用父类构造函数
this.age = age;
}
// 设置原型链
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
// 子类方法
Child.prototype.greet = function() {
Parent.prototype.greet.call(this); // 调用父类方法
console.log(`I am ${this.age} years old.`);
};
const child = new Child('Bob', 12);
child.greet();
// 输出:
// Hello, Bob!
// I am 12 years old.
使用 Object.setPrototypeOf
另一种方式是使用 Object.setPrototypeOf 动态设置原型链。
function Parent(name) {
this.name = name;
}
Parent.prototype.greet = function() {
console.log(`Hello, ${this.name}!`);
};
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
// 设置原型链
Object.setPrototypeOf(Child.prototype, Parent.prototype);
Child.prototype.greet = function() {
Parent.prototype.greet.call(this);
console.log(`I am ${this.age} years old.`);
};
const child = new Child('Charlie', 8);
child.greet();
// 输出:
// Hello, Charlie!
// I am 8 years old.
注意事项
- 使用
class和extends是推荐的方式,代码更清晰且易于维护。 - 手动设置原型链时,需确保正确调用父类构造函数(如
Parent.call(this))并修复constructor属性。 - 避免直接修改
__proto__,使用Object.create或Object.setPrototypeOf更安全。
以上方法可以根据需求选择适合的方式实现 JavaScript 的继承功能。






