介绍&总结

记录在以后的使用过程中,发现的不同和用法。

  1. callapplybind都用于改变 this 绑定
  2. callapply 在改变 this 指向的同时还会执行函数,一次性的。不同的是 call方法传递函数调用形参是以散列形式,而 apply 方法的形参是一个数组。在传参的情况下,call的性能要高于 apply,因为 apply 在执行时还要多一步解析数组。
  3. bind 在改变 this 后是返回一个全新的绑定函数,即返回一个新的函数,不直接执行函数。并且此后 this 的指向无法在通过 callapplybind 改变。

call

  • 方法使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数。

function.call(thisArg, arg1, arg2, ...)

  • [thisArg] 必选的,但是你也可以不写,但是不写,那你用这个方法还有什么意义?在 function 函数运行时使用的 this 值, 指定为 nullundefined 时会自动替换为指向全局对象
  • [arg1, arg2, ...] 参数列表

let objCall ={
    name: "我是 Call"
}


function fn() {
    console.log('参数 => ', ...arguments)
    console.log('name => ', this.name)
}

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

// 参数 =>  1 2 3
// name =>  我是Call

apply

  • 方法调用一个具有给定 this 值的函数,以及以一个数组(或类数组对象)的形式提供的参数。

func.apply(thisArg, [argsArray])

  • [thisArg] 必选的 同 call 一样
  • [argsArray] 可选的

let objApply ={
    name: "我是 Apply"
}
function fn() {
    console.log('参数 => ', ...arguments)
    console.log('name => ', this.name)
}
fn.apply(objApply, [1,2,3])
// 参数 =>  1 2 3
// name =>  我是 Apply


bind

  • 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。

function.bind(thisArg[, arg1[, arg2[, ...]]])

  • [thisArg]
  • [arg1, arg2, ...] 当目标函数被调用时,被预置入绑定函数的参数列表中的参数。
let objBind ={
    name: "我是 Bind"
}
let objApply ={
    name: "我是 Apply"
}

function fn() {
    console.log('参数 => ', ...arguments)
    console.log('name => ', this.name)
}
let bfn = fn.bind(objBind, 1,2,3);
bfn();

bfn.call(objCall)
bfn.apply(objApply)

// 三个结果一样
// 参数 =>  1 2 3
// name =>  我是 Bind

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐