call、apply、bind 的区别是什么?
请说明 call、apply、bind 三个方法的区别、传参方式和使用场景。
回答
屠龙少年
共同点:都用于显式指定函数执行时的 this 指向。
区别:
| 方法 | 执行时机 | 传参方式 | 返回值 |
|---|---|---|---|
call | 立即执行 | 参数列表 (thisArg, arg1, arg2, ...) | 函数执行结果 |
apply | 立即执行 | 数组/类数组 (thisArg, [argsArray]) | 函数执行结果 |
bind | 返回新函数 | 参数列表(可预填部分参数) | 返回绑定了 this 的新函数 |
使用场景:
- call:借用方法
Array.prototype.slice.call(arguments) - apply:参数是数组时
Math.max.apply(null, [1, 2, 3]) - bind:固定 this 上下文(React 事件绑定)、函数柯里化
注意:
bind返回的新函数,this 不能被call/apply再次修改(除new外)- 箭头函数的 this 无法被这三种方法改变