区别
- 三者都可以改变函数的
this指向。
- 三者第一个参数都是
this要指向的对象,如果没有这个参数或者参数为undefined或者null,则默认指向全局window
- 三者都可以传参,但是
apply传入的是数组,call传入的是参数列表。
apply和call一次传入所有参数,bind可以一次传入部分参数,下次调用返回的函数时再传入其他参数。
- bind是返回绑定
this后的函数,用于后续调用。apply``call是立即执行绑定this后的函数。
实现
bind
Function.prototype.customBind = function (context, ...bindArgs) {
const self = this
return function (...args) {
const newArgs = bindArgs.concat(args)
return self.apply(context, newArgs)
}
}
function fn(a, b, c) {
console.log(this, a, b, c);
}
fn.customBind({ x: 100 }, 20, 30)
apply
Function.prototype.customApply = function (context, argsArray) {
if (context == null) context = globalThis
if (typeof context !== 'object') context = new Object(context)
const fnKey = Symbol()
context[fnKey] = this
const res = context[fnKey](...argsArray)
delete context[fnKey]
return res
}
call
Function.prototype.customCall = function (context, ...callArgs) {
if (context == null) context = globalThis
if (typeof context !== 'object') context = new Object(context)
const fnKey = Symbol()
context[fnKey] = this
const res = context[fnKey](...callArgs)
delete context[fnKey]
return res
}
function test(a, b, c) {
console.log(this, a, b, c);
}
test.customCall({ x: 100 }, 20, 30)