likes
comments
collection
share

JS 进阶 | 关于 call、apply、bind

作者站长头像
站长
· 阅读数 11

在 JS 中,使用 apply()call()bind() 可以改变 this 指向。在很多手写代码来实现某个方法的时候,经常会出现对它们的使用。

改变 this 指向,即改变函数执行时的上下文,执行后会指向其传入的参数

apply

当函数调用 apply 方法时,

  • this 会变成传入的 obj
  • 传入的参数必须是一个数组
  • 改变 this 指向后,原函数会立即执行,并且 apply 只是改变 this 指向一次
  • apply 的第一个参数为 null 或是 undefined 时,默认指向 window

执行如下代码:

function fn(){
    console.log(this,'this');
    console.log(arguments,'参数');
}
let obj = {
    name:"张三"
}

fn(1,2)
fn.apply(obj,[1,2]);

当直接执行 fn 函数时,this 指向的是 window:

JS 进阶 | 关于 call、apply、bind

当使用 apply 改变 this 指向后,指向了传入的对象 obj:

JS 进阶 | 关于 call、apply、bind

call

当函数调用 call 方法时,

  • 传入的是一个参数列表
  • 改变 this 指向后,原函数会立即执行,并且 call 只是改变 this 指向一次
  • call 的第一个参数为 null 或是 undefined 时,默认指向 window

执行如下代码:

function fn(){
    console.log(this,'this');
    console.log(arguments,'参数');
}
let obj = {
    name:"张三"
}

fn(1,2)
fn.call(obj,1,2);

可以看到与 apply 的运行结果是相同的:

JS 进阶 | 关于 call、apply、bind

bind

  • 改变 this 指向后不会立即执行
  • 返回值是一个永久改变 this 指向的函数

直接执行 fn(),this 指向 window。使用 bind 改变 this 指向时,

function fn(arguments){
    console.log(this,'this');
    console.log(arguments,'参数');
}
let obj = {
    name:"张三"
}
fn(1,2) 
const bindFn = fn.bind(obj);
bindFn(1,2)

运行结果:

JS 进阶 | 关于 call、apply、bind

总结

共同点

  • 都是用来改变函数的 this 指向
  • 第一个参数都是 this 要指向的对象 不同点:
  • apply、call 会立即执行函数,bind 不会立即执行
  • apply 参数师叔祖,call 参数是参数列表,bind 可以分多次传入