Home > Enterprise >  Having trouble understanding this context in Array.map callback
Having trouble understanding this context in Array.map callback

Time:10-18

I have the following snippet in a React component. This is a trivial example, but I'm trying to better my understanding of the this keyword and its context

const NAVBAR_ITEM_TITLES = ["Home", "About", "Contact"];

function makeNavbarItems() {
  return NAVBAR_ITEM_TITLES.map(item => ({
    title: item,
    handleButtonClick() {
      console.log(`clicked the ${this.title} button`);
    },
  }));
}

const Navbar = () => {
  const navbarItems = makeNavbarItems();

  return (
    <>
      {navbarItems.map(item => (
        <div>
          <button key={item.title} onClick={item.handleButtonClick}>
            {item.title}
          </button>
        </div>
      ))}
    </>
  );
};

I wrote a small function that returns some anonymous objects to populate a navbar. However, the this context inside the anonymous object that map returns is undefined. I understand that if I create a named object like myObj then I may access the title property such as myObj.title, but I'd like to gain understanding of what I'm doing wrong and how to fix it.

Cheers.

CodePudding user response:

You already have access to the item string, which you're aliasing it as title: there is no need to use this at all:

function makeNavbarItems() {
  return NAVBAR_ITEM_TITLES.map(item => ({
    title: item,
    handleButtonClick() {
      console.log(`clicked the ${item} button`);
    },
  }));
}

CodePudding user response:

this always refer to the object in the current context, and in this case, the new object you are creating with your prototype. As @Terry said, it's not really necessary here. In some case, you will need this to differentiate between two expression with the same name but on different scope. (e.g. A global variable and a local one of the same name).

  • Related