簡體   English   中英

高級函數如`map()`和`reduce()`如何接收數據?

[英]How do higher-order functions like `map()` and `reduce()` receive their data?

我正在嘗試編寫自己的高階函數,我想知道map()reduce()等函數如何訪問它們正在應用的數組。 不僅僅是數組,還有任何更高階的函數,如toString()toLowerCase()

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

array.myOwnFunction(/* data??? */)

我希望這是有道理的。 我肯定答案已經存在,但我很難知道要搜索什么來查找信息。

檢查polyfill的Array.prototype.map() ,特別是這一行:

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

簡化, 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); 

這種方式的工作方式與原型和“thisBinding”有關。

使用new實例化函數時,原型的屬性將附加到新的Function對象。 同樣,創建“執行上下文”以維護環境。 然后可以在環境中通過當前實例使用this綁定來訪問原型的屬性。

因此,如果您想要使用實例中的數據,您也可以使用原型。 由於許多原因(內存使用,可讀性,可重用性,繼承,多態性等),這是最好的方法。 通常不鼓勵修改標准實現,例如ArrayMathDate等(盡管總會有例外)。

 function LineItem(description,price,quantity){ this.description = description; this.price = price; this.quantity = quantity; } LineItem.prototype.Total = function(){ return this.price * this.quantity; }; var avocados = new LineItem("avocado",2.99,3); console.log(avocados.Total()); 

這里要帶走的主要事情是thisBinding允許通過this訪問當前實例的對象。 這就是數據訪問的來源。 例如,在數組實例中,它引用當前數組; 在日期實例中,它引用當前日期; 在上面的LineItem示例中,它引用了當前的LineItem。

感謝對這個問題的回答,我能夠編寫一個接受回調函數作為參數的高階組件。 以下是代碼示例:

 Array.prototype.myFunction = function (callback) { const items = this const newArray = [] for (let item of items) { item = callback(item) newArray.push(item) } return newArray } const array = [1, 2, 3, 4] const result = array.myFunction((item => { return item + 1 })) console.log(result) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM