call 和 apply 的使用讨论

关于这两个方法的使用,目前就理解到这,希望能抛砖引玉。下边代码复制是可以直接运行的。

使用形式:

1. a.fn.call(b,agrs1,agrs2,agrs3)

2. c.fn.apply(d,[agrs1,agrs2,...agrs3])

使用理解:切换函数的上下文,达到暂时调用不属于自己的方法的目的。


<script>
    function add(a,b) {
        return a+b;
    }
    function sub(a,b) {
        return a-b;
    }
        var a = add(10,11);
        var b = sub(20,3);
    console.log("a=",a,"b=",b)  // a= 21 b= 17
        a = add.call(sub,20,3)
    console.log("a=",a,"b=",b)  // a= 23 b= 17
        a = add.apply(sub,[20,3])
    console.log("a=",a,"b=",b)  // a= 23 b= 17
        var c = Math.max(1,23,4,54,65,76);
    console.log("c=",c)  // c = 76
        var d = [1,23,4,54,65,76]
        var e = Math.max.apply(Math,d)
    console.log("e=",e)  // e = 76

    function Obj1() {
        this.name = "obj1";
        this.age  = "12";
        this.fn1   = function () {
            console.log("name_1",this.name,"age_1",this.age);
        }
    }
    function Obj2() {
        this.name = "obj2";
        this.age  = "22";
        this.fn2   = function () {
            console.log("name_2",this.name,"age_2",this.age);
        }
    }
    var obj1 = new Obj1();
    Obj2.prototype = obj1;
    var obj2 = new Obj2();
    obj1.fn1();             // name_1 obj1 age_1 12
    obj2.fn2();             // name_2 obj2 age_2 22
    obj1.fn1.call(obj2);    // name_1 obj2 age_1 22
    obj2.fn1();             // name_1 obj2 age_1 22
</script>



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值