假設我有一個這樣的工廠:
const itemFactory = () => {
const itemName = ''
const firstMethod = () => {
// something goes here
}
return { itemName, firstMethod }
}
有沒有辦法可以跟蹤我使用該功能創建的專案數量?我想包括在索引itemName每個專案的屬性,如:item0,item1,item2等。
uj5u.com熱心網友回復:
您可以使用高階函式來實作:
const createItemFactory = () => {
let currentItem = 0;
return () => {
const itemName = 'item' currentItem ;
const firstMethod = () => {
// something goes here
}
return { itemName, firstMethod };
}
}
然后你可以創建一個itemFactory:
const itemFactory = createItemFactory();
const item0 = itemFactory();
console.log(item0.itemName); // item0;
const item1 = itemFactory();
console.log(item1.itemName); // item1;
閱讀有關 JavaScript 閉包的更多資訊
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/364771.html
標籤:javascript 目的 工厂方法
