js实现extends
实现继承的方式
在 JavaScript 中,可以通过多种方式实现继承。以下是几种常见的方法:
原型链继承
原型链继承通过将子类的原型指向父类的实例来实现继承。
function Parent() {
this.name = 'Parent';
}
Parent.prototype.getName = function() {
return this.name;
};
function Child() {
this.childName = 'Child';
}
Child.prototype = new Parent();
const child = new Child();
console.log(child.getName()); // 输出 'Parent'
构造函数继承
构造函数继承通过在子类构造函数中调用父类构造函数来实现继承。

function Parent(name) {
this.name = name;
}
function Child(name, childName) {
Parent.call(this, name);
this.childName = childName;
}
const child = new Child('Parent', 'Child');
console.log(child.name); // 输出 'Parent'
组合继承
组合继承结合了原型链继承和构造函数继承的优点。
function Parent(name) {
this.name = name;
}
Parent.prototype.getName = function() {
return this.name;
};
function Child(name, childName) {
Parent.call(this, name);
this.childName = childName;
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
const child = new Child('Parent', 'Child');
console.log(child.getName()); // 输出 'Parent'
原型式继承
原型式继承通过创建一个临时构造函数来实现继承。

function createObject(obj) {
function F() {}
F.prototype = obj;
return new F();
}
const parent = {
name: 'Parent',
getName: function() {
return this.name;
}
};
const child = createObject(parent);
console.log(child.getName()); // 输出 'Parent'
寄生式继承
寄生式继承在原型式继承的基础上增强了对象。
function createObject(obj) {
const clone = Object.create(obj);
clone.sayHello = function() {
console.log('Hello');
};
return clone;
}
const parent = {
name: 'Parent',
getName: function() {
return this.name;
}
};
const child = createObject(parent);
console.log(child.getName()); // 输出 'Parent'
child.sayHello(); // 输出 'Hello'
寄生组合式继承
寄生组合式继承是目前最理想的继承方式,避免了组合继承的缺点。
function inheritPrototype(child, parent) {
const prototype = Object.create(parent.prototype);
prototype.constructor = child;
child.prototype = prototype;
}
function Parent(name) {
this.name = name;
}
Parent.prototype.getName = function() {
return this.name;
};
function Child(name, childName) {
Parent.call(this, name);
this.childName = childName;
}
inheritPrototype(Child, Parent);
const child = new Child('Parent', 'Child');
console.log(child.getName()); // 输出 'Parent'
ES6 Class 继承
ES6 引入了 class 和 extends 关键字,使继承更加简洁。
class Parent {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
class Child extends Parent {
constructor(name, childName) {
super(name);
this.childName = childName;
}
}
const child = new Child('Parent', 'Child');
console.log(child.getName()); // 输出 'Parent'
选择继承方式的建议
- 如果需要简单的继承,可以使用原型链继承或构造函数继承。
- 如果需要更复杂的继承,推荐使用组合继承或寄生组合式继承。
- 在现代 JavaScript 开发中,优先使用 ES6 的
class和extends语法。
以上方法各有优缺点,根据具体需求选择合适的继承方式。






