我的 inventoryList()函数是这样调用的,我无法更改。
if (operationInfo[0] === 'add') {
inventoryList().add(operationInfo[1]);
但是我在我的 inventoryList 函数里面有一个方法,就像下面这样,但是它指出 obj.add 不是一个函数!为什么?
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
函数,你应该从你的 inventoryList
功能。
function inventoryList() {
const add = (name) => {
if (!(name in inv)) {
inv[name] = name;
entries.push(name)
}
};
return { add };
}
不过,如果你要这样使用它,我建议你把它的 inventoryList
上课 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
是不返回任何东西的。返回一个包含要执行的函数引用的对象。同时 _add
是一个内部函数,它是对 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>