JS 中 call、apply、bind 方法的区别

在 JavaScript 中,call、apply 和 bind 都是用来改变函数执行时 this 指向的方法,它们都存在于 Function.prototype 上,因此每个函数都可以调用这些方法。虽然它们的作用相似,但在使用方式上有一些区别。

省流总结

方法 调用时机 参数形式 返回值 是否立即执行
call 直接调用 参数逐个传递 原函数返回值 ✅ 是
apply 直接调用 数组形式参数 原函数返回值 ✅ 是
bind 不调用 参数逐个传递(预设) 绑定this的新函数 ❌ 否

注意: 箭头函数的 this 不可通过这些方法修改(因其基于词法作用域)

call()

  • 功能: 立即调用函数, 并指定函数内 this 指向和参数, 参数按顺序逐个传递
  • 语法: func.call(thisArg, arg1, arg2, ...)
    • thisArg: 函数运行时使用的 this 值 (必填)
    • arg1, arg2, ...: 参数按顺序逐个传递
  • 返回值: 函数本身的执行结果

示例

function greet(city) {
    return `${ this.name } from ${ city }`;
}

const person = {name: "Alice"};
console.log(greet.call(person, "Paris")); // "Alice from Paris"

apply()

  • 功能: 立即调用函数, 并指定函数内 this 指向和参数, 参数以数组形式传递
  • 语法: func.apply(thisArg, [argsArray])
    • thisArg: 函数运行时使用的 this 值 (必填)
    • argsArray: 参数数组([arg1, arg2, ...]),支持类数组对象
  • 返回值: 函数本身的执行结果

示例

const numbers = [5, 6, 2, 3];
const max = Math.max.apply(null, numbers); // 等同于 Math.max(5,6,2,3)
console.log(max); // 6

bind()

  • 功能: 非立即调用函数, 而是返回一个绑定了指定 this 和预设参数的新函数
  • 语法: func.bind(thisArg, arg1, arg2, ...)
    • thisArg: 新函数的 this 值 (必填)
    • arg1, arg2, ...: 预设参数(可选)
  • 返回值: 一个新的函数(原函数的拷贝), 其 this 被永久固定
  • 特点:
    • 可预设参数(柯里化), 调用新函数时可补充剩余参数
    • 绑定后无法再通过 call/apply 修改 this (硬绑定)

示例

const person = {name: "Bob"};

function showInfo(age, job) {
    return `${ this.name }, ${ age }, ${ job }`;
}

const boundFunc = showInfo.bind(person, 30); // 预设 age = 30
console.log(boundFunc("Engineer")); // "Bob, 30, Engineer"
posted @ 2025-06-24 00:59  mingleton  阅读(75)  评论(0)    收藏  举报