继承的实现js
原型链继承
通过让子类的原型对象指向父类的实例来实现继承。子类实例可以访问父类原型上的属性和方法。
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;
}
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();
const child = new Child('child');
child.sayName(); // 'child'
原型式继承
基于已有对象创建新对象,使用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.sayHi = function() {
console.log('hi');
};
return clone;
}
const parent = { name: 'parent' };
const child = createAnother(parent);
child.sayHi(); // 'hi'
寄生组合式继承
目前最理想的继承方式,只调用一次父类构造函数,避免在子类原型上创建不必要的属性。
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和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'






