最初的

Kratos
专注于用户阅读体验的响应式博客主题
  1. 首页
  2. 前端
  3. 正文

经典Bind,Apply,Call 三者的区别

2025年9月14日 674点热度 0人点赞 0条评论

1. 共同点

  • 作用:都可以改变函数调用时的 this 指向。
  • 用法:都在函数对象上调用,如 fn.bind(...) / fn.call(...) / fn.apply(...)。

2. 区别

① call

  • 语法:fn.call(thisArg, arg1, arg2, ...)
  • 作用:立即调用函数,this 指向 thisArg。
  • 参数传递:逐个传。
function greet(greeting, punctuation) {
  console.log(greeting + ', ' + this.name + punctuation);
}

const person = { name: 'Alice' };

greet.call(person, 'Hello', '!');
// 输出: Hello, Alice!

② apply

  • 语法:fn.apply(thisArg, [argsArray])
  • 作用:立即调用函数,this 指向 thisArg。
  • 参数传递:以数组形式传递(适合参数数量不确定时)。
greet.apply(person, ['Hi', '...']);
// 输出: Hi, Alice...

③ bind

  • 语法:const newFn = fn.bind(thisArg, arg1, arg2, ...)
  • 作用:不会立即调用,返回一个新函数,this 永久绑定为 thisArg。
  • 参数传递:可以在 bind 时预置一部分参数(柯里化)。
const greetAlice = greet.bind(person, 'Hey');
greetAlice('?');
// 输出: Hey, Alice?

3. 直观对比表

方法是否立即调用参数形式返回值
call✅ 立即调用单个参数列表函数执行结果
apply✅ 立即调用参数数组函数执行结果
bind❌ 不调用单个参数列表(可预置)新函数(this 被绑定)

4. 使用场景

  • call:快速调用并改变 this。 Array.prototype.forEach.call(document.querySelectorAll('div'), el => console.log(el));
  • apply:需要数组展开的场景。 Math.max.apply(null, [1, 5, 3]); // 5
  • bind:需要延迟调用 / 绑定事件回调时。 button.onclick = handler.bind(obj);
标签: 前端面试题
最后更新:2025年9月14日

skybreak

这个人很懒,什么都没留下

点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

归档

  • 2025 年 10 月
  • 2025 年 9 月
  • 2025 年 8 月

分类

  • NAT64
  • VPS测评
  • 前端
  • 前端面试题
  • 华为云考试
  • 教程
  • 未分类
  • 油猴插件
  • 纯IPV6
  • 羊毛

COPYRIGHT © 2025 最初的. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang