我在这里就不讲解这三个API的用法了,有需要请自行查看MDN文档
call
Function.prototype.myCall = function(context, ...args) {
if (typeof this !== 'function') {
throw new TypeError('Error')
}
context = context ?? window // 传进来的是null和undefined时将this指向为window
context = Object(context) // 确保传进来的是Object
// 生成一个唯一的key值,防止和传进来的对象的key重复
const key = Symbol()
context[key] = this
const result = context[key](...args)
delete context[key] // 删除手动添加的属性,使context回到最初的样子
return result
}
apply
Function.prototype.myApply = function (context, arrs) {
if (typeof this !== 'function') {
throw new TypeError('Error')
}
context = context ?? window // 传进来的是null和undefined时将this指向为window
context = Object(context) // 确保传进来的是Object
// 生成一个唯一的key值,防止和传进来的对象的key重复
const key = Symbol()
context[key] = this
const result = arrs ? context[key](...arrs) : context[key]()
delete context[key] // 删除手动添加的属性,使context回到最初的样子
return result
}
bind
Function.prototype.myBind = function(context, ...args1) {
if (typeof this !== 'function') {
throw new TypeError('Error')
}
return (...args2) => {
context = context ?? window // 传进来的是null和undefined时将this指向为window
context = Object(context) // 确保传进来的是Object
// 生成一个唯一的key值,防止和传进来的对象的key重复
const key = Symbol()
context[key] = this
const result = context[key](...args1, ...args2)
delete context[key] // 删除手动添加的属性,使context回到最初的样子
return result
}
}