原理:

借用构造函数传递参数和寄生模式实现继承

代码理解

  1. function inheritPrototype(subType, superType){
  2. const prototype = Object.create(superType.prototype);
  3. subType.constructor = subType;
  4. subType.prototype = prototype;
  5. }
  6. function superType(){
  7. this.name = 'z';
  8. this.hobby = ['小姐姐', '美女']
  9. }
  10. superType.prototype.getName = function(){ console.log(this.name) }
  11. function subType(age){
  12. this.age = age;
  13. superType.call(this);
  14. }
  15. subType.prototype.getAge = function(){ console.log(this.age) }
  16. inheritPrototype(subType, superType);
  17. let user = new subType(18);
  18. user.hobby.push('60岁富婆');
  19. let user1 = new subType(19);
  20. user1.hobby.push('70岁富婆');
  21. console.log(user.hobby) // ['小姐姐', '美女', '60岁富婆']
  22. console.log(user1.hobby) // ['小姐姐', '美女', '70岁富婆']

最佳解决方案

  • 目前最成熟的方案、很多库都是这样玩、高效率体现在只执行了一次superType、也避免了在原型和实例上都创建了一些不必要的属性、与此同时、原型链还能保存不变!