【问题标题】:Using Array Prototype Slice Call使用数组原型切片调用
【发布时间】:2013-07-20 03:11:18
【问题描述】:

以下代码(来自 msdn)是“绑定”功能的简单实现:

/* Approximation of `Function.prototype.bind` from ES5 (without error checking) */
Function.prototype.bind = function(thisArg) {
  var fn = this, args = *Array.prototype.slice.call(arguments, 1)*;
  return function() {
     return fn.apply(thisArg, args.concat(*Array.prototype.slice.call(arguments, 0)*));
  };
 };

谁能解释第一次调用 Array.prototype.slice.call 吗?我知道参数不是数组,在使用 slice 和 concat 之前需要将其转换为数组。我不明白第一次调用 - 我们在调用时不是丢失了第一个元素

Array.prototype.slice.call(arguments, 1)?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    你是对的。

    arguments 的第零个元素是thisArg,这就是它被删除的原因。

    【讨论】:

      【解决方案2】:

      根据有关bind 的文档,第一个参数(arguments[0])是自定义this 值,用作bind 返回的函数中this 的值(“绑定功能”)。

      接下来的 (arguments[1] - arguments[n]) 是调用绑定函数时要添加的参数,以及调用时提供的参数。

      第一个Array.prototype.slice.call 所做的是对传递给bind 调用的参数进行切片,并从传递的第二个参数开始将参数放在前面,留下第一个参数,即我们的this

      例如

      var newFN = someFunction.bind(myNewThis,foo,bar,baz);
      

      第一个Array.prototype.slice.call 采用foobarbaz

      在返回的函数中,foobarbaz 被添加到调用绑定函数时提供的参数之前:

      //fn - original function
      //args - extracted arguments foo, bar and baz
      //thisArg - the provided `this` value, myNewThis
      
      //this code basically:
      // - calls the original function (fn) 
      // - provides a custom `this` value (thisArg)
      // - provides arguments that comprise the extracted arguments + the passed arguments
      fn.apply(thisArg, args.concat(Array.prototype.slice.call(arguments, 0)));
      

      因此,当您使用新的“绑定”函数时,您会得到一个自定义的 this 值,以及一个“预设”的前置参数列表:

      newFN('ban','bam'); //arguments === ['foo','bar','baz','ban','bam'];
      

      【讨论】:

      • OK 澄清一点。但是,为什么需要将 args 与 fn.apply 中的参数连接起来?我认为,一旦我们创建了 args 变量,我们只需将其传递给 apply。
      猜你喜欢
      • 1970-01-01
      • 2011-10-09
      • 2012-11-10
      • 2016-09-19
      • 2020-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      相关资源
      最近更新 更多