代码实现
Function.prototype.call1 = function (context: any = window, ...args: any[]): any {
let result
const fnKey = Symbol()
context[fnKey] = this
result = context[fnKey](...args)
delete context[fnKey]
return result
}
Function.prototype.apply1 = function (context: any = window, args: any[]): any {
if (typeof context !== 'object') {
return this(...args)
}
let result
const fnKey = Symbol()
context[fnKey] = this
result = context[fnKey](...args)
delete context[fnKey]
return result
}
function fn(this: any, name: string) {
return 'name:' + name + '-' + 'age:' + this.age
}
const obj = {
age: 20
}
const callResult = fn.call1(obj, 'call', 21)
const applyResult = fn.apply1(obj, ['apply', 22])
console.log('callResult', callResult)
console.log('applyResult', applyResult)