之所以要写这篇,是因为曾经面试被要求在白纸上手写bind实现
结果跟代码一样清晰明确,一阵懵逼,没写出来!
下面,撸起袖子就是干!~
把call、apply、bind一条龙都整一遍!~~
call
定义与使用
Function.prototype.call(): https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/call
1 2 3 4 5 6 7 8
| function fun(arg1, arg2) { console.log(this.name) console.log(arg1 + arg2) } const _this = { name: 'YIYING' }
fun.call(_this, 1, 2)
|
手写实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
Function.prototype.ownCall = function(context, ...args) { context = (typeof context === 'object' ? context : window) const key = Symbol() context[key] = this const result = context[key](...args) delete context[key] return result }
|
1 2 3 4 5 6 7 8
| function fun(arg1, arg2) { console.log(this.name) console.log(arg1 + arg2) } const _this = { name: 'YIYING' }
fun.ownCall(_this, 1, 2)
|
apply
定义与使用
Function.prototype.apply(): https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
1 2 3 4 5 6 7 8
| function fun(arg1, arg2) { console.log(this.name) console.log(arg1 + arg2) } const _this = { name: 'YIYING' }
fun.apply(_this, [1, 2])
|
手写实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
Function.prototype.ownApply = function(context, args) { context = (typeof context === 'object' ? context : window) const key = Symbol() context[key] = this const result = context[key](...args) delete context[key] return result }
|
1 2 3 4 5 6 7 8
| function fun(arg1, arg2) { console.log(this.name) console.log(arg1 + arg2) } const _this = { name: 'YIYING' }
fun.ownApply(_this, [1, 2])
|
bind
定义与使用
- Function.prototype.bind()
- https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
1 2 3 4 5 6 7 8 9
| function fun(arg1, arg2) { console.log(this.name) console.log(arg1 + arg2) } const _this = { name: 'YIYING' }
const newFun = fun.bind(_this) newFun(1, 2)
|
手写实现
1 2 3 4 5 6 7 8 9 10 11
|
Function.prototype.ownBind = function(context) { context = (typeof context === 'object' ? context : window) return (...args)=>{ this.call(context, ...args) } }
|
1 2 3 4 5 6 7 8 9
| function fun(arg1, arg2) { console.log(this.name) console.log(arg1 + arg2) } const _this = { name: 'YIYING' }
const newFun = fun.ownBind(_this) newFun(1, 2)
|
最后,麻烦以后面试不要再考这道题了!~~~
留言
欢迎交流想法。留言会通过 GitHub Issues 保存,首次使用需要登录 GitHub。