- call
function foo(num1, num2) { return num1 + num2 } Function.prototype.hyCall = function(thisArg, ...argArray) { thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg) : window let fn = this const key = Symbol() thisArg[key] = fn let result = thisArg[key](...argArray) delete thisArg[key] return result } let result = foo.hyCall({ name: 'yyy' }, 20, 30) console.log(result)
2.apply
function foo(num1, num2, num3) { console.log('foo被调用了', this) return num1 + num2 + num3 } Function.prototype.hyBind = function (thisArg, ...argArray) { thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg) : window let fn = this return function (...args) { let key = Symbol() thisArg[key] = fn let result = thisArg[key](...argArray, ...args) delete thisArg[key] return result } } let fn = foo.bind({ name: 123 }, 1,2) let result = fn(3) console.log(result)
3.bind
function foo(num1, num2, num3) { console.log('foo被调用了', this) return num1 + num2 + num3 } Function.prototype.hyApply = function (thisArg, argArray) { thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg) : window let fn = this let key = Symbol() thisArg[key] = fn argArray = argArray ?? [] let result = thisArg[key](...argArray) delete thisArg[key] return result } let result = foo.hyApply(123,[1,2,3]) console.log(result)