手写apply、call、bind函数
实现apply、call函数
查看
1 | Function.prototype.zApply = function (thisArg, args = []) { |
1 | Function.prototype.zCall = function (thisArg, ...args) { |
以上代码存在相同之处,可以尝试对以上操作进行封装。
1 | Function.prototype.execute = function (thisArg, ...args) { |
手写实现的弊端:
-
以上是通过隐式绑定this机制实现的,但需要向调用者传入参数,这样会对外部产生影响,且容易覆盖原有对象的属性,虽然最后会将添加的属性删除,但对于thisArg所引用的对象来说,影响可能是很大的。
实现bind函数
查看
1 | Function.prototype.zBind = function (thisArg, ...args) { |
弊端:
-
和手写实现apply/call的思路基本相同,但为调用着添加了个属性,且不能对其删除,影响很大。