实现call和bind函数
实现call函数
思路
原理:函数作为对象的属性调用时,this指向对象
- 获取
thisArg参数和剩余参数 - 获取调用
call的函数,把该函数设置到thisArg.func属性上 - 执行thisArg.func函数,并接收函数执行后的结果result
- 移除thisArg上的func函数
- 返回执行结果
源码
1 | Function.prototype.myCall = function(thisArg, ...args) { |
测试
1 | function sayHello(time) { |
手写bind函数
思路
- 获取
thisArg和剩余参数args - 获取调用myBind的函数,保存到
func - 新建一个返回函数
resultFn,在resultFn中做如下逻辑- 获取执行resultFn时的secondArgs, 把之前的参数args和secondArgs做合并
- 判断是否使用new关键字执行resultFn函数
- 如果是,resultFn函数内部this不变
- 否则,resultFn函数内部this修改为
thisArg
- 通过apply执行
func函数,并返回执行结果 - 修改resultFn函数的原型,绑定到
Object.create(func.prototype)
源码
1 | Function.prototype.myBind = function(thisArg, ...args) { |
测试
1 | function Person(name, age) { |
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 mio博客!
评论
