需要弄清楚它是如何工作的,因为我无法修复程序错误。请有人解释那里发生了什么。以及为什么环境不是全球性的,为什么我不确定?
const inventory = {
items: ["Knife", "Gas mask"],
add(itemName) {
console.log(`Adding ${itemName} to inventory`);
console.log(this);
this.items.push(itemName);
},
remove(itemName) {
console.log(`Removing ${itemName} from inventory`);
this.items = this.items.filter((item) => item !== itemName);
},
};
const invokeInventoryAction = function (itemName, action) {
console.log(`Invoking action on ${itemName}`);
action(itemName);
};
invokeInventoryAction("Medkit", inventory.add);
// Invoking action on Medkit
// Adding Medkit to inventory
console.log(inventory.items); // ['Knife', 'Gas mask', 'Medkit']
invokeInventoryAction("Gas mask", inventory.remove);
// Invoking action on Gas mask
// Removing Gas mask from inventory
console.log(inventory.items); // ['Knife', 'Medkit']
输出:
task_2.js:6 Uncaught TypeError: Cannot read property 'items' of undefined
at add (task_2.js:6)
at invokeInventoryAction (task_2.js:16)
at task_2.js:19