bind call/apply 总结
初学小白的个人笔记整理😶🌫️
call/apply
共同点:
改变函数执行时的上下文,将一个对象的方法交给另一个对象来执行,并且是立即执行的。
区别:
call从第二个参数开始,可以接受任意个参数,每个参数会映射到相应位置的Function的参数上。
apply的第二个参数,必须是数组或者类数组,它们会被转换成类数组,传入 Function 中,并且会被映射到 Function 对应的参数上。
实现call
Function.prototype.myCall = function (context, ...args) {
if (context == null) context = globalThis //window
if (typeof context !== 'object') context = new Object(context) // 值类型,变为对象
const fnKey = Symbol() // 不会出现属性名称的覆盖
context[fnKey] = this // this 就是当前的函数
const res = context[fnKey](...args) // 绑定了 this
delete context[fnKey] //清理掉 fn,防止污染
return res;
}
实现apply
Function.prototype.myApply = function (context, args) {
if (context == null) context = globalThis //window
if (typeof context !== 'object') context = new Object(context) // 值类型,变为对象
const fnKey = Symbol() // 不会出现属性名称的覆盖
context[fnKey] = this // this 就是当前的函数
const res = context[fnKey](...args) // 绑定了 this
delete context[fnKey] //清理掉 fn,防止污染
return res;
}
bind
bind 方法 与 apply 和 call 比较类似,也能改变函数体内的 this 指向。不同的是,bind 方法的返回值是函数,并且需要稍后调用,才会执行。
实现bind
Function.prototype.myBind = function (context, ...bindArgs) {
// context 是bind 传入的this
// bindArgs 是 bind 传入的各个参数
const self = this // 当前的函数本身
return function (...args) {
//拼接参数
const newArgs = bindArgs.concat(args)
return self.apply(context, newArgs)
}
}