JS call与apply

在实际中call主要实现的传递对象和继承的功能

  //实现继承
        function people(name,age,like){
            this.name = name;
            this.sex = "";
            this.age = age;
            this.like = like;
            this.showInfo = function(){
                console.log("我叫"+this.name+"今年"+this.age+"性别"+this.sex+"爱好"+this.like);
            }
            ;        }
        function boy(name,age,like){
            people.call(this,name,age,like);
            this.sex = "男";
        }
        function girl(name,age,like){
            people.call(this,name,age,like);
            this.sex = "女";
        }
        var boy = new boy("张明",23,"足球");
        var girl = new girl("李雪",22,"购物");
        boy.showInfo();
        girl.showInfo();

//传递对象
        function people(){
            this.name = "姓名";
            this.age = 23;
            this.sex = "男";
            this.like = "玩";
            this.showInfo = function(){
              console.log("我叫"+this.name+"今年"+this.age+"性别"+this.sex+"爱好"+this.like);
            }
;        }
        function boy(name,age,like){
            this.name = name;
            this.age = age;
            this.sex = "男";
            this.like = like;
        }
        function girl(name,age,like){
            this.name = name;
            this.age = age;
            this.sex = "女";
            this.like = like;
        }
        var p = new people();
        var boy = new boy("张明",23,"足球");
        var girl = new girl("李雪",22,"购物");
        p.showInfo.call(boy);
        p.showInfo.call(girl);

apply在用法上和call相似,区别在于apply传递参数的传递两个参数(apply(this,[param[0],param[1])),call的传参方式是call(obj,param[0],param[1],param[2])。

     //apply的用法
        function people(name,age,like){
            this.name = name;
            this.sex = "";
            this.age = age;
            this.like = like;
            this.showInfo = function(){
                console.log("我叫"+this.name+"今年"+this.age+"性别"+this.sex+"爱好"+this.like);
            }
            ;        }
        function boy(name,age,like){
            people.apply(this,[name,age,like]);
            this.sex = "男";
        }
        function girl(name,age,like){
            people.apply(this,[name,age,like]);
            this.sex = "女";
        }
        var boy = new boy("张明",23,"足球");
        var girl = new girl("李雪",22,"购物");
        boy.showInfo();
        girl.showInfo();



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值