This is how my inventoryList() function is called and I cannot change it.
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? 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.
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.
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. Return an object which contains reference to the function you want to execute. Also _add
is an inner function which is private to inventoryList
so have to expose it to use it
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.