我不理解JS中的“此”方法

时间:2020-05-23 12:54:21

标签: javascript this environment

需要弄清楚它是如何工作的,因为我无法修复程序错误。请有人解释那里发生了什么。以及为什么环境不是全球性的,为什么我不确定?

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

0 个答案:

没有答案