我如何弄清楚在内置的javascript函数上调用和绑定的行为

时间:2020-09-18 01:06:09

标签: javascript bind

我试图理解此代码。 Array(8).fill(0).map(Number.call, Number)。问题在于,这种行为很难理解,因为无法看到数字的实现。如果尝试使用.toString Number,它将仅显示“本机代码”。将绑定和调用与内置函数一起使用时也是如此。我如何找出这种行为?

1 个答案:

答案 0 :(得分:2)

如果您想详细了解Number的工作原理,请查看其ECMAScript specs

如果您想了解Number的总体工作原理,请查看其MDN documentation

基本上,Number(value)所做的只是将value转换为数字类型。没什么。

我相信您需要了解的内容实际上是关于Function.prototype.call而不是Number

当我们将上面的代码转换成花哨的代码时,我们大致得到了这样的东西(这对于下面的解释很重要):

console.log(
  Array(8).fill(0).map(Function.prototype.call, Number)
);

现在,在.map中,它收到2个参数:

  1. 回调,带有3个参数:currentValuecurrentIndexoriginalArray
  2. 自定义this

因此,上面的代码所做的是传递Number.call作为回调,并传递Number作为自定义此值。

如果您了解.call方法,您将知道它必须至少接收1个参数:

  1. this值。
  2. ...参数 n

了解了所有这些信息之后,我们现在可以将上面的代码转换为更精美的代码:

console.log(
  Array(8).fill(0).map(function(currentValue, currentIndex, originalArray){
    return this.call(currentValue, currentIndex);
  }, Number)
);

这也可以翻译成花哨的东西:

console.log(
  // Making `currentValue` into `_` because its existence does not matter in this case
  Array(8).fill(0).map(function(_, currentIndex){
    return Number.call(_, currentIndex);
  })
);

现在,这是最容易理解的最终翻译:

console.log(
  Array(8).fill(0).map((_, i) => Number(i))
);