1.原型链继承
原型链继承是JavaScript中最常用的继承方式之一,它通过将子类的原型指向父类的实例来实现继承。这种方式的缺点是父类的引用类型属性会被所有子类实例共享,容易造成属性污染。
function Parent() {
this.name = 'parent';
}
Parent.prototype.sayName = function() {
console.log(this.name);
}
function Child() {
this.name = 'child';
}
Child.prototype = new Parent();
var child = new Child();
child.sayName(); // 输出 'child'
2.借用构造函数继承
借用构造函数继承是通过在子类的构造函数中调用父类的构造函数来实现继承。这种方式的缺点是不能继承父类原型链上的属性和方法。
function Parent() {
this.name = 'parent';
}
function Child() {
Parent.call(this);
this.name = 'child';
}
var child = new Child();
console.log(child.name); // 输出 'child'
3.组合继承
组合继承是将原型链继承和借用构造函数继承结合起来的一种继承方式。这种方式的优点是既能继承父类原型链上的属性和方法,又能避免父类引用类型属性被所有子类实例共享的问题。
function Parent() {
this.name = 'parent';
}
Parent.prototype.sayName = function() {
console.log(this.name);
}
function Child() {
Parent.call(this);
this.name = 'child';
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
var child = new Child();
child.sayName(); // 输出 'child'
3.原型式继承
原型式继承是通过创建一个临时构造函数,将一个对象作为该构造函数的原型,然后返回该构造函数的实例来实现继承。这种方式的缺点是容易造成属性污染。
function object(obj) {
function F() {}
F.prototype = obj;
return new F();
}
var parent = {
name: 'parent',
sayName: function() {
console.log(this.name);
}
};
var child = object(parent);
child.name = 'child';
child.sayName(); // 输出 'child'
5.寄生式继承
寄生式继承是在原型式继承的基础上,增加了一个包装函数,用于对继承对象进行扩展。这种方式的缺点是容易造成属性污染。
function createAnother(obj) {
var clone = Object.create(obj);
clone.sayName = function() {
console.log(this.name);
};
return clone;
}
var parent = {
name: 'parent'
};
var child = createAnother(parent);
child.name = 'child';
child.sayName(); // 输出 'child'
寄生组合式继承
盗用构造函数继承 + 原型式继承
function Super(){ this.a=[1,2] }
Super.prototype.say = function(){ console.log(‘hhh’) }
function Sub(){
Super.call(this)
this b=2
}
Sub.prototype = Object.create(Super.prototype)
Sub.prototype.constructor = Sub
const test = new Sub()
优点:集合了【原型式继承】和【盗用构造函数继承】的优点,效率比【组合继承】更高。