0

As far as I understand, "execution context" is determined by where a function is called — not where it is declared.

So in the example below I would expect this.name to evaluate to undefined. Thus I'm not sure how console.log() has access to the this keyword inside of the "franchise" object.

let franchise = {
  name: 'How to Train Your Dragon',
  allMovies: function() {
    console.log(this.name)
  },
};

franchise.allMovies() // How to Train Your Dragon

The reason I would expect it to evaluate to "undefined" is the same as in this example:

let franchise = {
  name: 'How to Train Your Dragon',
  allMovies: function() {
    function print() {
      return this.name;
    }
    return print(); //undefined
  }
};
bugsyb
  • 4,282
  • 7
  • 24
  • 37
  • "*So in the example below I would expect this.name to evaluate to undefined.*" why? – VLAZ May 20 '21 at 20:21
  • Added additional context to the question – bugsyb May 20 '21 at 20:27
  • Your second code returns `undefined` because of how `print` is called, not because of how `franchise.allMovoes()` is called. As a rule of thumb, when you execute a regular function with `()` the value of `this` becomes whatever is before the last `.`, so `a.b.c()` executes `.c()` with `this = a.b`; `a.b()` executes `.b()` with `this = a`; `a()` executes `a()` with `this = undefined` (which will be substituted with the global object in sloppy mode); `franchise.allMovies()` is in the `a.b()` form, so `this = franchise` while `print()` is in the `a()` form. – VLAZ May 20 '21 at 20:33

1 Answers1

0

this.name gets evaluated (that Dragon string) and passed as an argument to console.log. Console has nothing to do with this - just outputs its arguments.