原型链继承
function SubType(){
this.property = true;
}
SubType.prototype.get = function(){
return this.property;
}
function SuperType(){
}
SuperType.prototype = new SubType();
var ins = new SuperType();
缺点:
- 所有子类的实例对引用类型的操作会共享
- 子类型的原型上的constructor指向的是父类的构造函数
- 给子类型添加方法必须在替换子类原型后
- 创建子类型时无法向父类传参
借助构造函数继承
function SubType(){
this.property = true;
}
SubType.prototype.get = function(){
return this.property;
}
function SuperType(){
SuperType.call(this);
}
var ins = new SuperType();
优点:
- 可以给父类传参,并且不会重写子类的原型。
缺点 - 无法继承原型上的属性和方法。
组合继承
function SubType(name){
this.property = name;
}
SubType.prototype.get = function(){
return this.property;
}
function SuperType(name){
SuperType.call(this, name); //第二次调用父类
}
SuperType.prototype = new SubType(); //第一次调用父类,不用传参,第二次调用会覆盖第一次的实力属性
SuperType.prototype.constructor = SuperType;
var ins = new SuperType("a");
优点:
- 成功继承到父类的属性和方法。
缺点: - 调用两次父类,
原型式继承
function object(proto) {
function F() {}
F.prototype = proto;
return new F();
}
const cat = {
name: 'Lolita',
friends: ['Yancey', 'Sayaka', 'Mitsuha'],
say() {
console.log(this.name);
},
};
const cat1 = object(cat);
缺点:
- 导致引用类型被多个实例篡改
寄生式继承
const cat = {
name: 'Lolita',
friends: ['Yancey', 'Sayaka', 'Mitsuha'],
say() {
console.log(this.name);
},
};
function createAnother(original) {
const clone = Object.create(original); // 获取源对象的副本
clone.gender = 'female';
clone.fly = function() {
// 增强这个对象
console.log('I can fly.');
};
return clone; // 返回这个对象
}
const cat1 = createAnother(cat);
缺点:
- 引用类型被篡改,函数无法复用;
寄生组合式继承
function inheritPrototype(child, parent) {
const prototype = Object.create(parent.prototype); // 创建父类原型的副本
prototype.constructor = child; // 将副本的构造函数指向子类
child.prototype = prototype; // 将该副本赋值给子类的原型
}
function Vehicle(powerSource) {
this.powerSource = powerSource;
this.components = ['座椅', '轮子'];
}
Vehicle.prototype.run = function() {
console.log('running~');
};
function Car(wheelNumber) {
this.wheelNumber = wheelNumber;
Vehicle.call(this, '汽油');
}
inheritPrototype(Car, Vehicle);
Car.prototype.playMusic = function() {
console.log('sing~');
};
只是记录学习,参考自这里