js 实现 extends
实现 JavaScript 中的 extends 功能
在 JavaScript 中,extends 关键字用于实现类之间的继承。以下是几种实现继承的方式,包括 ES6 的 class 语法和传统的原型链继承方法。
使用 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\nI 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');
};
var child = new Child('Alice', 10);
child.greet(); // 输出: Hello, Alice\nI am 10 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');
};
var child = new Child('Alice', 10);
child.greet(); // 输出: Hello, Alice\nI am 10 years old
使用混合继承(组合继承)
组合继承结合了原型链继承和构造函数继承的优点。
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 = new Parent();
Child.prototype.constructor = Child;
// 添加子类方法
Child.prototype.greet = function() {
Parent.prototype.greet.call(this);
console.log('I am ' + this.age + ' years old');
};
var child = new Child('Alice', 10);
child.greet(); // 输出: Hello, Alice\nI am 10 years old
使用 extends 与自定义行为
可以通过覆盖 extends 的行为来实现更复杂的继承逻辑。
class CustomParent {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Custom Hello, ${this.name}`);
}
}
class CustomChild extends CustomParent {
constructor(name, age) {
super(name);
this.age = age;
}
greet() {
super.greet();
console.log(`Custom I am ${this.age} years old`);
}
}
const customChild = new CustomChild('Alice', 10);
customChild.greet(); // 输出: Custom Hello, Alice\nCustom I am 10 years old
以上方法提供了多种实现 JavaScript 继承的方式,可以根据具体需求选择适合的方式。






