js难题记录

Function.prototype.bind = Function.prototype.bind || 
function (context, ...args1) {
var _this = this

return function(...args2) {
return _this.call(context, ...args1, ...args2)
}
}
// bind,实现的机制就是Currying.
var a  = {
 
      name: 'a',
 
      getName: function () {
 
      console.log(this.name);
 
      }
 
      }
 
      var b = {
 
      name : 'b'
 
      }
 
      var c =  {
 
      name: 'c'
 
      }
 
      var fn1 = a.getName.bind(b);
 
      var fn2 = a.getName.bind(b).bind(c);

运行以下代码

 fn1(); // b

 fn2(); // b(为什么???)

 a.getName(); // a

 2020.06.17补充

之前对于fn2()运行结果为b表示不理解,最近找到了答案

因为多次bind绑定只有第一次生效

原因是,在Javascript中,多次 bind() 是无效的。更深层次的原因, bind() 的实现,相当于使用函数在内部包了一个 call / apply ,第二次 bind() 相当于再包住第一次 bind() ,故第二次以后的 bind 是无法生效的。

原文地址:https://www.cnblogs.com/LeoXnote/p/13048228.html