Open dragonwong opened 7 years ago
先别让我去 UC,先看看这段代码:
const objA = { num: 1, }; const objB = { num: 2, }; function fn() { console.log(this.num); } fn = fn.bind(objA); fn = fn.bind(objB); fn();
答案是啥?
竟然是...
1
在 @malcolmyu 同学的点拨下,猜测 bind 方法的实际返回一个内部使用 call 的匿名函数:
bind
call
function bind(fn, context) { return function() { fn.call(context); }; }
下面通过实现 mybind 方法模拟 bind:
mybind
Function.prototype.mybind = function(context) { return () => { this.call(context); } }
验证下:
Function.prototype.mybind = function(context) { return () => { this.call(context); } } const objA = { num: 1, }; const objB = { num: 2, }; function fn() { console.log(this.num); } fn = fn.mybind(objA); fn = fn.mybind(objB); fn(); // 打印 1
哈哈,一毛一样。
先别让我去 UC,先看看这段代码:
答案是啥?
竟然是...
1
在 @malcolmyu 同学的点拨下,猜测
bind
方法的实际返回一个内部使用call
的匿名函数:下面通过实现
mybind
方法模拟bind
:验证下:
哈哈,一毛一样。