javascript的继承之简单粗暴

继承概念:

继承就是让一个类拥有另一个类的属性和方法

继承方式

方式一:
通过原型继承,给需要继承的对象换原型

 function Fun(){
       this.music="唱";
       this.run="跳";
       this.firend=function(){
           console.log("giao");          
       }
    }
    function Fn(){
        this.name="鸡你太美";
    }
    //让Fn类的原型赋值为Fun实例化的对象(new 出来的那个对象)  给Fn原型赋值
    Fn.prototype=new Fun();
    var fn=new Fn();   
    console.log(fn);//fn对象就继承了Fun类的属性和方法   

在这里插入图片描述
此时fn的constructor属性指向的构造函数是Fun,可以手动设置回去

fn.constructor=Fn;

方式二
使用上下文调用模式(借用函数继承)

function Fun(){
       this.music="唱";
       this.run="跳";
       this.firend=function(){
           console.log("giao");          
       }
    }
    function Fn(){
        this.name="鸡你太美";
        Fun.call(this);//改变Fun中的this指向,并立即执行
        //Fun.apply(this) 改变Fun中的this指向,并立即执行
        //Fun.bind(this)()//改变Fun中的this指向,并返回新函数
    }

缺点:
如果继承的这个类中的属性和方法绑定在原型上,那么这种继承方式不能继承原型上的方法和属性

方式三:
组合继承(原型继承+上下文调用)

function Fun(){
       this.music="唱";
       this.run="跳";
       this.firend=function(){
           console.log("giao");          
       }
    }
    function Fn(){
        this.name="鸡你太美";
        Fun.call(this);//改变Fun中的this指向,并立即执行
        //Fun.apply(this) 改变Fun中的this指向,并立即执行
        //Fun.bind(this)()//改变Fun中的this指向,并返回新函数
    }
    Fn.prototype=new Fun();
     //如果只需要Fun上的原型对象的方法或属性,并且Fun没啥用了,可以直接把Fun的原型赋值给Fn,即
    //Fn.prototype=Fun.prototype;
    Fn.prototype.constructor=Fn;//将Fn原型的构造函数改回Fn

方式四:
class类继承

class Fun{
        //定义对象的属性都在constructor方法中
        constructor(){
            this.music="唱";
            this.run="跳";
        }
        //方法
        friend(){
            console.log("鸡你太美");
        }
    }
    class Fn extends Fun{//使用extends关键字继承
        constructor(){
            // 如果父类有constructor,子类这里必须调用super()这个方法
            super();//这里其实是在执行父类的constructor()方法
            this.name="giao";
        }
    }

方式五:
在子类中调用父类继承

function Fun(){
       this.music="唱";
       this.run="跳";
       this.firend=function(){
           console.log("giao");          
       }
    }
    function Fn(){
        this.name="鸡你太美";
        //调用父类
        this.fun=Fun;
        this.fun();
    }
    console.log(new Fn());
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值