实现 Function 的原生方法
大约 1 分钟
bind 方法
- 参数有
thisArg
和原函数的参数args
- 若
thisArg
为undefined
,则赋值全局对象window
- 支持衔接后续传入的参数
otherArgs
interface Function {
myBind(thisArg: any, ...args: any[]): any
}
Object.defineProperty(Function.prototype, 'myBind', {
enumerable: false,
writable: false,
configurable: false,
value: function myBind(this: Function, thisArg: any, ...args: any[]): any {
const _self = this
thisArg = thisArg || window
return function(...otherArgs: any[]) {
return _self.apply(thisArg, args.concat(otherArgs))
}
}
})
Function.prototype.myBind = function(thisArg, ...args) {
thisArg = thisArg || window
const _self = this
return function(...otherArgs) {
return _self.apply(thisArg, args.concat(otherArgs))
}
}
call 方法
- 参数有
thisArg
和原函数的其他参数args
- 若
thisArg
为undefined
,则赋值全局对象window
interface Function {
myCall(thisArg: any, ...args: any[]): any
}
Object.defineProperty(Function.prototype, 'myCall', {
enumerable: false,
writable: false,
configurable: false,
value: function myCall(this: Function, thisArg: any, ...args: any[]): any {
thisArg = thisArg || window
thisArg._fn = this
const result = thisArg._fn(...args)
delete thisArg._fn
return result
}
})
Function.prototype.myCall = function(thisArg, ...args) {
thisArg = thisArg || window
thisArg._fn = this
const result = thisArg._fn(...args)
delete thisArg._fn
return result
}
apply 方法
- 参数有
thisArg
和原函数的参数数组args
- 若
thisArg
为undefined
,则赋值全局对象window
interface Function {
myApply(thisArg: any, args?: any[]): any
}
Object.defineProperty(Function.prototype, 'myApply', {
enumerable: false,
writable: false,
configurable: false,
value: function myApply(this: Function, thisArg: any, args?: any[]): any {
let result: unknown
thisArg = thisArg || window
thisArg._fn = this
if (args) {
result = thisArg._fn(...args)
} else {
result = thisArg._fn()
}
delete thisArg._fn
return result
}
})
Function.prototype.myApply = function(thisArg, args) {
let result
thisArg = thisArg || window
thisArg._fn = this
if (args) {
result = thisArg._fn(...args)
} else {
result = thisArg._fn()
}
delete thisArg._fn
return result
}