loading...

re: JavaScript: Creeping into this (Exercise) VIEW POST

FULL DISCUSSION
 

That was a tough adventure. Couple of my answers were wrong for the first time.
After some thinking here are my solutions.
Two things to keep in mind:

  1. Arrow functions are lexical scoped (i.e. don't have their own this)
  2. Take a look at who called a function to find out it's this. Usually it's an object to the left of a dot.

Ex 1
When a function is defined in global scope, it's defined in window object. outer() is the same as window.outer(), so the caller is window object. arrow function have the same this as outer, so the answer is window.

Ex 2
New execution contexts (including this) are created on function calls. Objects don't create new execution contexts, so the execution contexts stack here is the same as in Ex1, and the answer is window.

Ex 3
window again!

Ex 4
init function is called by object, so this for init is object.

Ex 5
This example is slightly harder than the previous one. setTimeout delays a callback execution. When it's time for the function to execute, who is the caller of this function? Right, it's window object!

Ex 6
Again, the anonymous function in then is executed by window, and the answer is window.

Ex 7
This example can be simplified to

(function() {
  const object = {
    whoIsThis: function() {
      console.log(this);
    }
  };
  object.whoIsThis();
})()

And based on the previous examples, it's clear that the answer is inner object.

 
code of conduct - report abuse