正文
Tips:call
bind
apply
对箭头函数来说,会忽略掉第一个参数,也就是this
指向参数,所以不会改变箭头函数this
的指向
call
实现this
指向绑定- 传参
- 返回值,看了很多的实现例子,都没有写这个。如果缺少返回值,那么对很多函数的模拟实现
call
就不会成功,尤其是函数具有返回值的时候,比如Object.prototype.toString.call()
thisArg
为null
或者undefined
时,会指向全局对象
Function.prototype.myCall = function (thisArg) {
const globalObj = typeof window === 'undefined' ? global : window
thisArg = thisArg ? thisArg : globalObj
thisArg[this.name] = this
const args = [...arguments].slice(1)
const val = thisArg[this.name](...args)
delete thisArg[this.name]
return val
}
apply
- 相比
call
来说,唯一的不同点就是传给原函数的参数类型是数组或是伪数组或是其它可转化为数组的数据类型
- 相比
Function.prototype.myApply = function (thisArg, argsArr) {
if (typeof argsArr !== 'object') {
throw new Error('CreateListFromArrayLike called on non-object')
}
const globalObj = typeof window === 'undefined' ? global : window
thisArg = thisArg ? thisArg : globalObj
thisArg[this.name] = this
console.log(Array.from(argsArr))
const val = thisArg[this.name](...Array.from(argsArr))
delete thisArg[this.name]
return val
}
bind
实现-
函数的柯里化
-
const fn = this
要在返回函数的外侧保存一下this
,不然返回函数内部this
指向为全局对象 -
在这里不用判断
thisArg
是否为空,因为之后会调用apply
,它会处理的 -
bind
关于new
的特性,待补充(懒)
-
Function.prototype.myBind = function (thisArg) {
const args = [].splice.call(arguments, 1)
const fn = this
return function () {
fn.apply(thisArg, [...args, ...arguments])
}
}
结语
如果对你有帮助的话,请点一个赞吧