0

Let us say there is a code block like

const Person = function (name, hobbies) {
  this.name = name;
  this.hobbies = hobbies;
  this.display = function () {
        //hobbies array iterated through the map function
    this.hobbies.map(function (hobby) {
            //Inside this anonymous function, the 'this.name' cannot be found
      console.log(`My name is ${this.name} & my hobby is ${hobby}`);
    });
  };
};

const hobbies = ['Sports', 'Music'];

const me = new Person('Skay', hobbies);

me.display();

Here while console.log(this.name) (inside the map function) apparently it creates a scope and this.name is assigned undefined. My understanding of scope chain is that it will try to find that variable in the outer scope. Also because of closure the this.name should have been accessible too because inner functions should have access to the outer function. Why is this not working like that and why is it that we need to use explicit binding.

leo
  • 83
  • 5
  • `this` is set by the calling context, but the calling context of the `.map` callback is not the instance. `this` is not lexically inherited (like variable scope) except with arrow functions; with full `function`s, `this` depends fully on the calling context; its outer scope doesn't matter. – CertainPerformance Aug 27 '20 at 04:08

0 Answers0