20190115问:
Call,Apply,Bind的使用与区别,如何实现一个bind?
相同点:
- 都是使用于方法借用及明确this指向场景
- 第一个参数都是this要指向的对象
- 都可以利用后续参数传参
不同点:
- 参数传递方式不同
- call,apply是立即调用,bind是动态调用
基本使用:
Array.prototype.slice.call(obj,0,1,2)Array.prototype.slice.apply(obj,[0,1,2])Array.prototype.slice.bind(obj)(0,1,2)复制代码
从上面的例子可以看出来call,apply 使用上几乎保持一致,而bind实际上是返回了一个函数
简易bind实现
Function.prototype.bind = function(context){ const _this = this return function() { _this.apply(context, Array.prototype.slice.call(arguments)) }}复制代码
上面的bind只实现了方法的作用域绑定,参数已经固定,如果想要动态的参数我们得改写一下
Function.prototype.bind = function(context){ const _this = this const argus = Array.prototype.slice.apply(arguments,[1]) return function() { _this.apply(context, argus.concat(Array.prototype.slice.call(arguments))) }}复制代码
往期
关于JS每日一题
JS每日一题可以看成是一个语音答题社区
每天利用碎片时间采用60秒内的语音形式来完成当天的考题 群主在次日0点推送当天的参考答案- 注 绝不仅限于完成当天任务,更多是查漏补缺,学习群内其它同学优秀的答题思路