Function 的 apply、call、bind
title: Function 的 apply、call、bind id: 57c5655b87c2f3efa66c908ce0a5cc04 tags: [] date: 2000/01/01 00:00:00 updated: 2023/03/04 19:29:12 isPublic: true --#|[分隔]|#--
apply 和 call
call()方法的作用和 apply() 方法类似,区别就是call()方法接受的是参数列表,而apply()方法接受的是一个参数数组。
apply 和 call 将调用前面的方法,但调用时,方法中的 this 指定为第一个参数,后面参数则是其他额外的参数。
感觉 apply 和 call 就像是「借鸡生蛋」,借别人的方法,来处理自己的东西。
语法:
function.apply(thisArg, [arg_1, arg_2, arg_3, ...])
function.call(thisArg, arg_1, arg_2, arg_3, ...)
thisArg:必选的,函数运行时使用的 this,请注意,如果这个函数处于非严格模式下,则指定为 null 或 undefined 时会自动替换为指向全局对象,原始值会被包装。
arg_1、arg_2...:可选,参数们
简单用法(更多用法可查看官方文档中的示例):
let arr = [1, 2, 3]
let arr_2 = [4, 5, 6]
let temp = []
temp.push.apply(arr, arr_2) // 等同于 temp.push.call(arr, ...arr_2)
console.log(temp) // []
console.log(arr) // [1, 2, 3, 4, 5, 6]
/**
* 虽然调用的是 temp.push
* 但由于是使用了 apply 或 call,push 方法内部的 this 代表的是 arr,而不是 temp
* 所以改变的也就是 arr 了
*/
bind
bind():方法创建一个原函数的拷贝,并拥有指定的 this(第一个参数)值和初始参数,而其余参数将作为新函数的参数,供调用时使用。
如果说 apply 和 call 是「借鸡生蛋」,那 bind 简直是「借鸡生蛋」的典范。
apply 和 call 起码还是立即执行函数,把鸡接过来立马下蛋然后立马还回去。
而 bind 则是生成一个指定了 this 的新函数,自己适时执行,相当于把鸡拿过来扣着,需要的时候就让鸡下一个蛋,令人发指。。。不过好用程度也是杠杠的。
语法:
const newFn = function.bind(thisArg, arg_1, arg_2, arg_3...)
thisArg:必选的,函数运行时使用的 this,如果使用new运算符构造绑定函数,则忽略该值。当使用 bind 在 setTimeout 中创建一个函数(作为回调提供)时,作为 thisArg 传递的任何原始值都将转换为 object。如果 bind 函数的参数列表为空,或者thisArg是null或undefined,执行作用域的 this 将被视为新函数的 thisArg。
arg_1、arg_2...:可选,参数们
bind() 函数会创建一个新的绑定函数(bound function,BF)。
绑定函数是一个 exotic function object(怪异函数对象,ECMAScript 2015 中的术语),它包装了原函数对象。调用绑定函数通常会导致执行包装函数。
绑定函数具有以下内部属性:
[[BoundTargetFunction]]:包装的函数对象
[[BoundThis]]:在调用包装函数时始终作为 this 值传递的值。
[[BoundArguments]]:列表,在对包装函数做任何调用都会优先用列表元素填充参数列表。
[[Call]]:执行与此对象关联的代码。通过函数调用表达式调用。内部方法的参数是一个this值和一个包含通过调用表达式传递给函数的参数的列表。
当调用绑定函数时,它调用 [[BoundTargetFunction]] 上的内部方法 [[Call]]: Call(boundThis, args)
boundThis:即 [[BoundThis]]
args 是 [[BoundArguments]] 加上通过函数调用传入的参数列表
绑定函数也可以使用 new 运算符构造,它会表现为目标函数已经被构建完毕了似的。
提供的 this 值会被忽略,但前置参数仍会提供给模拟函数。
bind 时不添加额外参数的用法示例(更多用法可查看官方文档中的示例):
let arr = [1, 2, 3]
let arr_2 = [4, 5, 6]
let temp = []
let push = temp.push.bind(arr)
// 没有变化,因为 push 还没有执行
console.log(temp) // []
console.log(arr) // [1, 2, 3]
// 适时执行
push(...arr_2)
console.log(temp) // []
console.log(arr) // [1, 2, 3, 4, 5, 6]
bind 时添加了额外参数的用法示例:
// bind 时的额外参数,再适时执行时,作为前几个参数传入方法中
let arr = [1, 2, 3]
let arr_2 = [4, 5, 6]
let temp = []
let push = temp.push.bind(arr, 10, 11, 12)
// 适时执行
push(...arr_2)
console.log(arr) // [1, 2, 3, 10, 11, 12, 4, 5, 6]
Last updated
Was this helpful?