JavaScript中call和apply的区别

136 阅读2分钟

JavaScript中call和apply的区别

在 JavaScript 中,callapply 都是用于显式绑定函数执行时的 this 值的方法。它们的主要区别在于 传递参数的方式

  1. call 方法
  • 作用:调用函数,并显式指定函数内部的 this 值,同时以 参数列表 的形式传递参数。

  • 语法

    func.call(thisArg, arg1, arg2, ...);
    
    • thisArg:函数运行时 this 的值。
    • arg1, arg2, ...:传递给函数的参数列表。
  • 示例

    function greet(name, age) {
        console.log(`Hello, ${name}! You are ${age} years old.`);
        console.log(this); // { country: "USA" }
    }
    
    const context = { country: "USA" };
    greet.call(context, "Alice", 25);
    // 输出:
    // Hello, Alice! You are 25 years old.
    // { country: "USA" }
    
  1. apply 方法
  • 作用:调用函数,并显式指定函数内部的 this 值,同时以 数组或类数组 的形式传递参数。

  • 语法

    func.apply(thisArg, [argsArray]);
    
    • thisArg:函数运行时 this 的值。
    • argsArray:传递给函数的参数数组(或类数组对象)。
  • 示例

    function greet(name, age) {
        console.log(`Hello, ${name}! You are ${age} years old.`);
        console.log(this); // { country: "Canada" }
    }
    
    const context = { country: "Canada" };
    greet.apply(context, ["Bob", 30]);
    // 输出:
    // Hello, Bob! You are 30 years old.
    // { country: "Canada" }
    
  1. callapply 的区别
特性callapply
参数传递方式参数列表 的形式传递数组或类数组 的形式传递
适用场景参数数量固定时使用参数数量不固定或动态时使用
  1. 使用场景

(1) call 的使用场景

  • 当参数数量固定且较少时,使用 call 更直观。
function add(a, b) {
    return a + b;
}
const result = add.call(null, 2, 3); // 5

(2) apply 的使用场景

  • 当参数数量不固定或动态时,使用 apply 更方便。
function sum() {
    return Array.from(arguments).reduce((acc, val) => acc + val, 0);
}
const numbers = [1, 2, 3, 4];
const result = sum.apply(null, numbers); // 10
  1. 实际应用

(1) 借用方法

  • 使用 callapply 可以借用其他对象的方法。
const obj1 = { name: "Alice" };
const obj2 = { name: "Bob" };

function greet() {
    console.log(`Hello, ${this.name}!`);
}

greet.call(obj1); // Hello, Alice!
greet.call(obj2); // Hello, Bob!

(2) 处理类数组对象

  • 使用 apply 可以将类数组对象(如 argumentsNodeList)转换为数组。
function logArguments() {
    const args = Array.prototype.slice.call(arguments);
    console.log(args);
}
logArguments(1, 2, 3); // [1, 2, 3]

总结

  • call:适合参数数量固定的场景,参数以列表形式传递。
  • apply:适合参数数量不固定或动态的场景,参数以数组形式传递。
  • 两者都可以显式绑定 this 值,是 JavaScript 中灵活调用函数的重要工具。

更多vue相关插件及后台管理模板可访问vue admin reference,代码详情请访问github