#javaScript基础 # 方法调用之apply和call的区别

119 阅读1分钟

使用方式

apply

  • 调用方式 func.apply(thisArg, [argsArray])

  • 参数:

    • thisArg 函数运行时指向 this ,传入对象可以修改 this 指向,用于限定函数执行的环境(上下文)

    • [argsArray] 表示函数的参数的数组

    var testVal = {name : "applyDemo"};
    var demo_func = function (a, b, c){
        console.log(a);
        console.log(b + c);
        console.log(this);
    }
    demo_func.apply(null, [1, 2, 3]);
    demo_func.apply(testVal, [1, 2, 3]);
    

    执行结果

call

  • 调用方式 func.call(thisArg, arg1, arg2, arg3, ... )
  • 参数:
    • thisArg 运行时会使用的 this 值,用于指定函数的执行环境(上下文)

    • arg1, arg2, arg3, ... 指定参数列表

        window.name = "123456abc";
        var testVal = {name : "applyDemo"};
        var testVal02 = {name : "applyDemo02"};
        
        var demo_func = function (a, b, c){
            console.log(a);
            console.log(b + c);
            console.log(this.name);
        }
        
        demo_func.call(null, 1, 2, 3);
        demo_func.call(testVal, 1, 2, 3);
        demo_func.call(testVal02, 1, 2, 3);

执行结果