/*
call(thisObj, ...args) 函数用来改变函数 this对象的指向
参数:
thisObj:可选,函数 this对象的指向 一个对象,如果 thisObj 未传递则为 window
args:可选:调用函数的入参
返回值:
改变函数 this 对象之后 调用函数的结果
思路:
1. 如果 thisObj 未传递则为 全局对象 window
2. 将要调用的函数作为 thisObj 的一个临时方法去调用,此时就改变了函数 this对象的指向
注意:这个函数对应的新添加的方法的属性key应该是独一无二的,所以可以用 Symbol
3. 调用 thisObj 的方法,并传入参数 args,返回一个结果 result
4. 删除给 thisObj 对象设置的临时方法 this
5. 返回值:result
*/
Function.prototype.myCall = function(thisObj, ...args) {
// 被改变 this对象指向 的函数就是 this
thisObj = thisObj || window
let newFnKey = Symbol()
thisObj[newFnKey] = this
let result = thisObj[newFnKey](...args)
delete thisObj[newFnKey]
return result
}
// 测试代码
function fullName(age) {
return `My name is ${this.firstName} ${this.lastName}, Age ${age}`
}
let myInfo = {
firstName: 'jia',
lastName: 'ru'
}
let myFullName = fullName.myCall(myInfo, 18)
console.log('myFullName == ', myFullName) // My name is jia ru, Age 18
JS手写 call 方法
于 2024-05-04 15:28:32 首次发布