继承的实现js
原型链继承
通过原型链实现继承是 JavaScript 中最基本的继承方式。子类的原型对象指向父类的实例,从而继承父类的属性和方法。
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child() {
this.childName = 'Child';
}
// 继承实现
Child.prototype = new Parent();
const child = new Child();
child.sayName(); // 输出: Parent
构造函数继承
使用 call 或 apply 方法在子类构造函数中调用父类构造函数,实现属性继承。这种方法无法继承父类原型上的方法。
function Parent(name) {
this.name = name;
}
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
const child = new Child('Tom', 10);
console.log(child.name); // 输出: Tom
组合继承
结合原型链继承和构造函数继承的优点,既能继承父类实例属性,也能继承父类原型方法。

function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function() {
console.log(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('Tom', 10);
child.sayName(); // 输出: Tom
原型式继承
通过 Object.create() 方法实现继承,创建一个新对象,使用现有对象作为新对象的原型。
const parent = {
name: 'Parent',
sayName: function() {
console.log(this.name);
}
};
const child = Object.create(parent);
child.name = 'Child';
child.sayName(); // 输出: Child
寄生式继承
在原型式继承的基础上增强对象,返回增强后的对象。

function createAnother(original) {
const clone = Object.create(original);
clone.sayHello = function() {
console.log('Hello');
};
return clone;
}
const parent = {
name: 'Parent'
};
const child = createAnother(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.sayName = function() {
console.log(this.name);
};
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
inheritPrototype(Child, Parent);
const child = new Child('Tom', 10);
child.sayName(); // 输出: Tom
ES6 Class 继承
ES6 引入了 class 语法糖,使用 extends 关键字实现继承更加简洁。
class Parent {
constructor(name) {
this.name = name;
}
sayName() {
console.log(this.name);
}
}
class Child extends Parent {
constructor(name, age) {
super(name);
this.age = age;
}
}
const child = new Child('Tom', 10);
child.sayName(); // 输出: Tom






