Search code examples
javascriptreferencethiswindow-object

this. references Object instead of Window-Object


I have an Object like shown below.

On line 6 I write console.log(this.title, elem).

Now according to what I learned about this.-Keyword, this.title shouldn't reference the current Object here, but the global Window-Object. Now contrary to my knowlede, this.title seems to correctly reference the property of the video-Object.

const video = {
    title: "a",
    tags: ["a", "b", "c", "d"],
    showTags() {
        this.tags.forEach(elem => {
            console.log(this.title + ": ", elem)
        });
    }
}
video.showTags();

This is what the Browser shows:

a:  a
a:  b
a:  c

I thought, that since console.log(this.title, elem) is inside a callBack-Function, a reference to the Global Window-Object would be made. This post confirms my notion that this.title should actually reference the Global Object.

Could somebody explain?


Solution

  • Arrow functions lexically bind their context so this actually refers to the originating context. Since you are using Arrow function here, the value of this inside the forEach() method points to the lexical environment in which it is declared. That is inside the showTags() method, so it has same this value as that of showTags().

    If arrow function was not used here, then the value of this would be window, as in the snippet below:

    const video = {
        title: "a",
        tags: ["a", "b", "c", "d"],
        showTags() {
            this.tags.forEach(function(elem ) {
                console.log(this.title, elem)
            });
        }
    }
    video.showTags();