像`map()`和`reduce()`这样的高阶函数如何接收它们的数据?

Jos*_*sey 6 javascript

我现在正在尝试编写自己的高阶函数,我想知道函数是如何喜欢map()reduce()访问它们所应用于的数组的。而且不仅仅适用于数组,还具有任何更高阶的函数,例如toString()toLowerCase()

array.map()
^^^ // How do I get this data when I am writing my own higher order function?

array.myOwnFunction(/* data??? */)
Run Code Online (Sandbox Code Playgroud)

我希望这是有道理的。我确定答案已经存在,但我一直在努力寻找要查找的信息以查找信息。

sil*_*ntw 5

检查polyfill的Array.prototype.map(),尤其是此行:

//  1. Let O be the result of calling ToObject passing the |this| 
//    value as the argument.
var O = Object(this);
Run Code Online (Sandbox Code Playgroud)

简化this是接收值的地方。


Tak*_*aki 5

您可以将其添加到Array原型中,例如:

Array.prototype.myOwnFunction = function() {
  for (var i = 0; i < this.length; i++) {
    this[i] += 1;
  }

  return this;
};

const array = [1, 2, 3];

const result = array.myOwnFunction();

console.log(result);
Run Code Online (Sandbox Code Playgroud)