簡體   English   中英

無法訪問其他 function 內部的 function

[英]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.

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