js中call、apply、bind大比拼
透彻讲解 JavaScript 中 call
、apply
、bind
的用法与区别
核心目标
这三个方法都是为了动态改变函数执行时的 this
指向,但用法和场景有所不同。通过类比和代码示例,快速掌握它们的本质区别。
一、共同点:改变 this
的指向
JavaScript 中函数的 this
默认指向调用它的对象,但通过 call
、apply
、bind
可以强制改变 this
的指向,实现“借用其他对象的方法”或“绑定上下文”。
二、call
和 apply
:立即调用函数
1. call
的用法
func.call(thisArg, arg1, arg2, ...)
- 作用:立即调用函数
func
,并显式指定this
为thisArg
,参数逐个传递。 - 示例:
function greet(name, age) { console.log(`${ name}, ${ age}岁,来自${ this.city}`); } co