手写简单call、apply、bind
1、call
~function(){ function call_1(context, ...args){ context = context == undefined ? window : context; let type = typeof context; if(!/^('object|function')$/.test(type)){ if(/^('bigint | symbol')$/.test(type)){ context = Object(context) }else{ context = new context.constructor(context) } } let key = Symbol('key'); context[key] = this; let result = context[key](...args); delete context[key]; return result; } Function.prototype.call_1 = call_1 }()
2、apply
~function(){ function apply_1(context, args){ context = context == undefined ? window : context; Array.isArray(args)?args:[]; let type = typeof context; if(!/^('object|function')$/.test(type)){ if(/^('bigint | symbol')$/.test(type)){ context = Object(context) }else{ context = new context.constructor(context) } } let key = Symbol('key'); context[key] = this; let result = context[key](...args); delete context[key]; return result; } Function.prototype.apply_1 = apply_1 }()
3、bind
~function(){ function bind_1(context, ...args){ context = context == undefined ? window : context; Array.isArray(args)?args:[]; let type = typeof context; if(!/^('object|function')$/.test(type)){ if(/^('bigint | symbol')$/.test(type)){ context = Object(context) }else{ context = new context.constructor(context) } } let _this = this return function(...innerArgs){ _this.call(context, ...args.concat(innerArgs) } } Function.prototype.bind_1 = bind_1 }()