实现继承js
实现继承的方式
在JavaScript中,继承可以通过多种方式实现。以下是几种常见的继承方法:
原型链继承
通过将子类的原型对象指向父类的实例来实现继承。子类可以访问父类的属性和方法。
function Parent() {
this.name = 'parent';
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child() {}
Child.prototype = new Parent();
const child = new Child();
child.sayName(); // 输出 'parent'
构造函数继承
在子类的构造函数中调用父类的构造函数,使用call或apply方法改变this指向。
function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function() {
console.log(this.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.sayName = function() {
console.log(this.name);
};
function Child(name) {
Parent.call(this, name);
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
const child = new Child('child');
child.sayName(); // 输出 'child'
原型式继承
通过一个函数创建一个临时构造函数,将其原型指向传入的对象,返回该构造函数的实例。
function createObject(obj) {
function F() {}
F.prototype = obj;
return new F();
}
const parent = {
name: 'parent',
sayName: function() {
console.log(this.name);
}
};
const child = createObject(parent);
child.sayName(); // 输出 'parent'
寄生式继承
在原型式继承的基础上增强对象,返回一个经过扩展的对象。

function createAnother(obj) {
const clone = Object.create(obj);
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) {
Parent.call(this, name);
}
inheritPrototype(Child, Parent);
const child = new Child('child');
child.sayName(); // 输出 'child'
ES6 Class继承
使用class和extends关键字实现继承,语法更简洁。
class Parent {
constructor(name) {
this.name = name;
}
sayName() {
console.log(this.name);
}
}
class Child extends Parent {
constructor(name) {
super(name);
}
}
const child = new Child('child');
child.sayName(); // 输出 'child'
每种继承方式各有优缺点,选择适合场景的方式实现继承。






