我现在正在尝试编写自己的高阶函数,我想知道函数是如何喜欢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)
我希望这是有道理的。我确定答案已经存在,但我一直在努力寻找要查找的信息以查找信息。
检查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是接收值的地方。
您可以将其添加到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)
| 归档时间: |
|
| 查看次数: |
71 次 |
| 最近记录: |