继承实现js
在 JavaScript 中,继承可以通过多种方式实现,主要包括原型链继承、构造函数继承、组合继承、原型式继承、寄生式继承和寄生组合式继承。以下是这些方法的详细说明和示例代码:
原型链继承
原型链继承是通过将子类的原型对象指向父类的实例来实现继承。子类可以访问父类原型上的属性和方法。
function Parent() {
this.name = 'Parent';
}
Parent.prototype.getName = function() {
return this.name;
};
function Child() {}
Child.prototype = new Parent();
const child = new Child();
console.log(child.getName()); // 输出: Parent
构造函数继承
构造函数继承通过在子类构造函数中调用父类构造函数来实现继承。这种方式可以避免引用类型的属性被所有实例共享。

function Parent(name) {
this.name = name;
}
function Child(name) {
Parent.call(this, name);
}
const child = new Child('Child');
console.log(child.name); // 输出: Child
组合继承
组合继承结合了原型链继承和构造函数继承的优点,既能继承父类原型上的方法,又能避免引用类型属性的共享问题。
function Parent(name) {
this.name = name;
}
Parent.prototype.getName = function() {
return this.name;
};
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
const child = new Child('Child', 10);
console.log(child.getName()); // 输出: Child
原型式继承
原型式继承通过创建一个临时构造函数来实现继承,类似于原型链继承,但更简洁。

function createObj(o) {
function F() {}
F.prototype = o;
return new F();
}
const parent = {
name: 'Parent',
getName: function() {
return this.name;
}
};
const child = createObj(parent);
console.log(child.getName()); // 输出: Parent
寄生式继承
寄生式继承在原型式继承的基础上增强对象,返回一个增强后的对象。
function createObj(o) {
const clone = Object.create(o);
clone.sayHello = function() {
console.log('Hello');
};
return clone;
}
const parent = {
name: 'Parent'
};
const child = createObj(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, age) {
Parent.call(this, name);
this.age = age;
}
inheritPrototype(Child, Parent);
const child = new Child('Child', 10);
console.log(child.getName()); // 输出: Child
ES6 Class 继承
ES6 引入了 class 和 extends 关键字,使继承更加简洁和直观。
class Parent {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
class Child extends Parent {
constructor(name, age) {
super(name);
this.age = age;
}
}
const child = new Child('Child', 10);
console.log(child.getName()); // 输出: Child
以上方法涵盖了 JavaScript 中实现继承的主要方式,开发者可以根据具体需求选择合适的方法。






