call 和 apply 的使用讨论

来源:互联网 发布:最好软件培训学校 编辑:程序博客网 时间:2024/05/14 07:20

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

使用形式:

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>