原理:
借用构造函数传递参数和寄生模式实现继承
代码理解
function inheritPrototype(subType, superType){
const prototype = Object.create(superType.prototype);
subType.constructor = subType;
subType.prototype = prototype;
}
function superType(){
this.name = 'z';
this.hobby = ['小姐姐', '美女']
}
superType.prototype.getName = function(){ console.log(this.name) }
function subType(age){
this.age = age;
superType.call(this);
}
subType.prototype.getAge = function(){ console.log(this.age) }
inheritPrototype(subType, superType);
let user = new subType(18);
user.hobby.push('60岁富婆');
let user1 = new subType(19);
user1.hobby.push('70岁富婆');
console.log(user.hobby) // ['小姐姐', '美女', '60岁富婆']
console.log(user1.hobby) // ['小姐姐', '美女', '70岁富婆']
最佳解决方案
- 目前最成熟的方案、很多库都是这样玩、高效率体现在只执行了一次superType、也避免了在原型和实例上都创建了一些不必要的属性、与此同时、原型链还能保存不变!