javascript中的prototype、call、apply、bind

  • js中继承有几种方式,下面介绍4种,分别是prototype、call、apply、bind
  • 一、prototype(原型)
//通过将父对象的构造函数的实例放在子对象的原型中,实现继承。
//原型继承
    function person(name,age,sex,job){
        this.name=name;
        this.age=age;
        this.sex=sex;
        this.job=job;
    }
    person.prototype={                
        say(){
            console.log("我们人都会说话");
        },
        eat(){
            console.log("我们人都会吃饭");
        },
    }
    function father(){
        this.name="刘备";
    }
    father.prototype=new person("刘邦",60,"男","皇上");
    let son=new father();
    son.name="刘备";
    console.log(son);
  • 二、call
//将父对象的某一个方法暂时借给子对象,并且会立即执行
//将父对象的构造函数整个继承给子对象
//call继承
     function father(){
         this.name="动物";
         this.say=function (a,b,c){
             alert("我是"+a+",我今年"+b+"岁了,我是最聪明的"+c)
         };
    }
    function son(){

    }
    let dad=new father();
    let sson=new son();
    //call继承整个父对象
    father.call(sson);
    sson.say("一只狗",18,"狗");
    //call继承父对象的一个属性或方法
    dad.say.call(sson,"一只猫",18,"猫");
  • 三、apply
//用法与call相同
//不同的是apply传递参数的时候将参数放在一个数组中传递;call会将参数一个一个用逗号隔开进行传
//apply继承
     function father(){
         this.name="动物";
         this.say=function (a,b,c){
             alert("我是"+a+",我今年"+b+"岁了,我是最聪明的"+c)
         };
    }
    function son(){

    }
    let dad=new father();
    let sson=new son();
    //apple继承整个父对象
    father.apply(sson);
    sson.say("一只猫",18,"猫");
    //apple继承父对象的一个属性或方法
    dad.say.apply(sson,["一只猫",18,"猫"]);

*四、bind

//bind用法于call,apply相同,不同的是bind不能继承整个构造函数。bind的继承结国会返回函数本身,不会立即执行
//bind符合我们正常的需求,可以将继承来的方法保存,当需要使用的时候再进行调用
    function father(){
         this.name="动物";
         this.say=function (a,b,c){
             alert("我是"+a+",我今年"+b+"岁了,我是最聪明的"+c)
         };
    }
    function son(){

    }
    let dad=new father();
    let sson=new son();
    let a=dad.say.bind(sson);
    a("一只猫",18,"猫")
上述方法只用做参考有什么不对的地方,请留言,以便于参考修改
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值