JS this 2

What will be logged?

by Gustavo

JavaScript

/*** What will be logged? ***/


/* Inside functions, using function keyword */
function foo() {
	console.log("1", this); 
}
//foo(); // Window object (reference to global object), undefined in strict mode

/* Inside objects */
const person = {
	name: 'Gustavo',
  call() {
  	console.log("2", this); 
  },
  callRegular: function() { console.log("3", this) }, 
  callArrow: () => console.log("4", this) 
}
person.call(); // person object (reference to object)
person.callRegular(); // person object
//person.callArrow(); // Window


/* Inside classes */
class Animal {
  call() {
  	console.log("5", this); 
  }
  nested() {
  	const regular = function() { console.log("6", this) };
    const arrow = () => console.log("7", this);
    regular();
    arrow();
  }
}
const animal = new Animal();
animal.call();  // animal object (reference to the instance of the class)
animal.nested(); // undefined y animal object


/* Function inside method */
class Animal2 {
  call() {
  	[1,2].map(function(item) { console.log(this) }); // undefined
    [1,2].map(item => console.log(this)); // animal2 object
  }
}
const animal2 = new Animal2();
animal2.call();