JavaScript: Creeping into this (Exercise)

Valentino Gagliardi - Jul 15 '19 - - Dev Community

For each exercise try to guess the output. What this points to, and more important, why? (Assuming the code is running in a browser).

Ex. #1:

function outer() {
  const arrow = () => console.log(this);
  arrow();
}

outer();
Enter fullscreen mode Exit fullscreen mode

Ex. #2:

function outer() {
  const obj = {
    init: () => console.log(this)
  };

  obj.init();
}

outer();
Enter fullscreen mode Exit fullscreen mode

Ex. #3:

const obj = {
  nested: {
    init: () => console.log(this)
  }
};

obj.nested.init();
Enter fullscreen mode Exit fullscreen mode

Ex. #4:

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

object.init();
Enter fullscreen mode Exit fullscreen mode

Ex. #5:

const object = {
  init: function() {
    setTimeout(function() {
      const arrow = () => console.log(this);
      arrow();
    }, 5000);
  }
};

object.init();
Enter fullscreen mode Exit fullscreen mode

Ex. #6:

const object = {
  init: function() {
    setTimeout(function() {
      fetch("https://jsonplaceholder.typicode.com/todos/").then(function() {
        const arrow = () => console.log(this);
        arrow();
      });
    }, 5000);
  }
};

object.init();
Enter fullscreen mode Exit fullscreen mode

Ex. #7:

const object = {
  init: function() {
    setTimeout(function() {
      const object = {
        whoIsThis: function() {
          console.log(this);
        }
      };
      object.whoIsThis();
    }, 5000);
  }
};

object.init();
Enter fullscreen mode Exit fullscreen mode

Put your solutions in the comments below!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .