继承 ---寄生式继承和寄生组合式继承
寄生式继承
function obj(o){ function F(){} F.prototype=o; return new F(); } function createPerson(orig){ var thePerson=obj(orig); thePerson.sayHi=function(){ console.log('hi'); }; thePerson.sex='female'; return thePerson; } var person={ name:"zhangsan", age:18, friends:['Lisi','wangwu','zhaoliu'] }; var newPerson=createPerson(person); newPerson.sayHi(); //hi console.lo g(newPerson.friends); //["Lisi", "wangwu", "zhaoliu"] console.log(newPerson.sex); //female
函数不能复用,降低效率,但新对象不仅具有person的属性和方法,还有自己的方法。
寄生组合式继承
function obj(o){ function F(){} F.prototype=o; return new F(); } function inheritPro(subType,superType){ var pro=obj(superType.prototype); pro.constructor=subType; subType.prototype=pro; } function SuperType(name){ this.name=name; this.friends=['Lisi','wangwu','zhaoliu']; } SuperType.prototype.sayName=function(){ console.log(this.name); }; function SubType(name,age){ SuperType.call(this,name); this.age=age; }; inheritPro(SubType,SuperType); var thePerson=new SubType('sunmenghua',24); console.log(thePerson.age); //24 console.log(thePerson.friends) // ["Lisi", "wangwu", "zhaoliu"]
计生组合式继承是引用类型最理想的继承
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步