[英]Cannot access the function inside the other function
這就是我的inventoryList() function 的調用方式,我無法更改它。
if (operationInfo[0] === 'add') {
inventoryList().add(operationInfo[1]);
但是我的inventoryList function 中有一個方法,如下所示,但它指出obj.add 不是function? 為什么?
function inventoryList(){
const add = (name) => {
// adds string to inv and if item exists doesn't add. Adds to log also as objects maintain no position
if(!(name in inv)){
inv[name] = name;
entries.push(name)
}
};
}
為了使用add
function,您應該從您的inventoryList
列表中返回 function。
function inventoryList() {
const add = (name) => {
if (!(name in inv)) {
inv[name] = name;
entries.push(name)
}
};
return { add };
}
不過,如果您打算這樣使用它,我建議將inventoryList
更改為class,並使用add
作為其方法。
class InventoryList {
add(name) {
if (!(name in inv)) {
inv[name] = name;
entries.push(name)
}
}
}
你可以像這樣使用它
const invList = new InventoryList();
if (operationInfo[0] === 'add') {
invList.add(operationInfo[1]);
}
inventoryList
沒有返回任何東西。 返回一個 object,其中包含對您要執行的 function 的引用。 另外_add
是一個內部 function ,它是inventoryList
私有的,所以必須公開它才能使用它
function execute() { inventoryList().add('hello') } function inventoryList() { const _add = (name) => { console.log(name) // rest of code }; return { add: _add, // add other function if it is there } }
<button onclick='execute()'>Execute</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.