2

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?

laruiss
  • 3,477
  • 1
  • 14
  • 27
Josh
  • 43
  • 6

1 Answers1

3

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();
laruiss
  • 3,477
  • 1
  • 14
  • 27
amrender singh
  • 6,982
  • 3
  • 17
  • 25
  • 1
    I just tried it and indeed... the `arrow`-function makes all the difference. I always thought that arrow-Notation was just a matter of syntax-refinement. Thank you! – Josh Apr 30 '19 at 18:44
  • @Josh You can mark an answer accepted by the checkmark to help others finding better answers. – FZs Apr 30 '19 at 18:52
  • I didn't realize that I was allowed to do that as a rookie-poster. Is just did now. – Josh Apr 30 '19 at 19:35