Inheriting "this" keyword

Hi,

I ran into an issue in js basci course at function section part 11-Chaniging this at the end mosh says that arrow function inherit “this” from the containing function and i didn’t quite understand that.
Can someone please explain how it works ?

Here’s the code :

  const video = {

      title: "a",

      tags: ["a", "b", "c"],

      showTags() {

        this.tags.forEach((tag) => console.log(this.title, tag));

      },

    };

    video.showTags();

Thanks in advance :heart:

The argument passed to the forEach() function is a function (a call back) When the call back executes “this” will be bound to the global object in Node or the window object in the browser, not the “video” object. By using the new arrow function syntax “this” does not get re-bound, so still refers to the “video” object.

If you execute the code below, you will see that “this.title” is undefined. In effect it is calling “global.title”, “window.title” not “video.title”

const video = {
  title: 'a',
  tags: ['a', 'b', 'c'],

  showTags() {
    this.tags.forEach(function (tag) {
      console.log(this.title, tag);
      console.log(this);
    });
  },
};

video.showTags();

A better way to implement showTags() would be:

const video = {
  title: 'a',
  tags: ['a', 'b', 'c'],

  showTags() {
    for (const tag of this.tags) console.log(this.title, tag);
  },
};

video.showTags();
1 Like

Still didn’t answer how the arrow function inherit the “this” keyword.
I want to know how it inherits “this” from the containing function

Arrow functions don’t bind their own scope, but inherit it from the parent one, which in this case is video.

1 Like

Let’s see this in actual examples.

class Cat {
    name;
    constructor(name) { this.name = name; }

    getName() {
        return this.name; // "this" can refer to other objects when rebinded. 
    }

    getNameArrow = () => {
        return this.name; // "this" will always refer to the original object.
    }
    
}

let me show what does rebinding mean:

const tigger = new Cat("Tigger");
const charlie = new Cat("Charlie");

then let’s swap their methods:

charlie.getName = tigger.getName;
tigger.getNameArrow = charlie.getNameArrow;

Now Charlie is using the normal method(function) from Tigger, while Tigger is using the arrow function from Charlie.

let’s see what will happen if we get their name:

charlie.getName();
// Charlie

tigger.getNameArrow();
// Charlie

So what is going on here? Since “this” reference in arrow functions will always refer to the “this” on its creation, even it is being assigned to other objects, it will still refer to the original object it belongs to.

In contrast, normal methods(which actually are functions) can be reassigned to other objects and the “this” reference will refer to the new owner. Search “javascript function binding” can give you more information.

1 Like