简体   繁体   English

无法访问其他 function 内部的 function

[英]Cannot access the function inside the other function

This is how my inventoryList() function is called and I cannot change it.这就是我的inventoryList() function 的调用方式,我无法更改它。

 if (operationInfo[0] === 'add') {
            inventoryList().add(operationInfo[1]);

But I have a method inside my inventoryList function like below but it states obj.add is not a function?但是我的inventoryList function 中有一个方法,如下所示,但它指出obj.add 不是function? why?为什么?

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)
        }
      };
}

In order to use the add function, you should return if from your inventoryList function.为了使用add function,您应该从您的inventoryList列表中返回 function。

function inventoryList() {
   const add = (name) => {
      if (!(name in inv)) {
         inv[name] = name;
         entries.push(name)
      }
   };

   return { add };
}

Althought, if you are going to use it like that, I recommend changing the inventoryList to class with add as its method.不过,如果您打算这样使用它,我建议将inventoryList更改为class,并使用add作为其方法。

class InventoryList {
   add(name) {
      if (!(name in inv)) {
         inv[name] = name;
         entries.push(name)
      } 
   }
}

You can than use it like this你可以像这样使用它

const invList = new InventoryList();

if (operationInfo[0] === 'add') {
   invList.add(operationInfo[1]);
}

inventoryList is not returning anything. inventoryList没有返回任何东西。 Return an object which contains reference to the function you want to execute.返回一个 object,其中包含对您要执行的 function 的引用。 Also _add is an inner function which is private to inventoryList so have to expose it to use it另外_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