实现多继承

本文介绍了JavaScript中如何实现多继承,通过`Object.create()`和`Object.assign()`结合使用,实现类的多重继承。示例代码展示了一个子类同时继承自两个父类的场景,并详细解释了原型链的工作原理,包括方法的调用和属性的访问。同时,文章提到了浅拷贝的潜在问题,提醒在处理原型属性时需要注意深拷贝的情况。
摘要由CSDN通过智能技术生成

实现多继承

function fathercalass(hobby,height){
    this.hobby=hobby
    this.height=height
}
fathercalass.prototype={
    hobbya:'debugger',
    settimea:function(){
        console.log('sgdop')
    }   
 }
function superclass(name,age){
    this.name0=name
    this.age0=age
 }
 superclass.prototype={
     agea:'kfj',
     setget:function(){
         console.log('setget1')
         return this         //  支持链式调用
     }
 }
 function sonclass(name,age,hobby,height){
     superclass.call(this,name,age)
     fathercalass.call(this,hobby,height)
 }
 sonclass.prototype=Object.create(Object.assign(fathercalass.prototype,superclass.prototype))   // 将两个原型的属性和方法合并后传递
 var obj1= new sonclass('akj',23,'basketball','table')
 console.log(obj1.agea,obj1.age0,obj1.name0)  // 输出 kfj 23 akj
 console.log(obj1.__proto__)       //  包含了superclass 和fatherclass的原型上的方法和属性的对象
 console.log(obj1.setget().setget().setget())  // return this  支持链式调用
 console.log(obj1.hobby,obj1.height)  //  输出 basketball table

只是将类式继承升级成了多继承 原理一样 注意 该处的Object.creat()和assign()都是属于浅拷贝 如果 原型属性中存在嵌套情况 请使用深拷贝

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值