js实现继承
原型链继承
利用原型链实现继承的基本思想是通过原型将一个引用类型继承另一个引用类型的属性和方法。构造函数、原型和实例之间的关系可以用原型链来表示。
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) {
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, age) {
Parent.call(this, name);
this.age = age;
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
const child = new Child('child', 10);
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, age) {
Parent.call(this, name);
this.age = age;
}
inheritPrototype(Child, Parent);
const child = new Child('child', 10);
child.sayName(); // 输出: child






