Question
Why console logging this in an arrow function inside a method logs the object and when set as a method object it shows {}
?
Answer
Being based on the review task
- Find the value of
this
in a function inside of a method.
Remember what was mentioned in this lesson and this topic, the meaning of this on a method or a declared function will relate to the calling object and if it is an arrow function, it will always be the lexical context where the function exists, for example:
const obj = {
name: 'boop',
showTime(){
(() => console.log(this))();
///here we have a method showtime calling an anonymous arrow function that is also
//just being made
},
logger: () => console.log(this), // here there is a property that is
//storing an arrow function
loging(){
console.log(this) // and here a method calling the console.log method
//which could count as a function
}
}
obj.showTime() //calling the first one will give us the following as a result:
//{ name: 'boop',
// showTime: [Function: showTime],
// logger: [Function: logger],
// loging: [Function: loging] }
Here’s why: the method’s meaning of this
is the calling object (obj
) and since we are creating and calling the anonymous arrow function inside the method, its enclosing lexical context (ie, its global scope is the object obj
where the method that is calling it exists. what about:
obj.logger() // it will return:
// {}
The reason is the same as before the arrow function will resonate with the global scope of the object obj
therefore the space the file is being processed will be the global scope object ( commonly, that global scope will be the browser window, the object is called window
). This is why your arrow function assigned to a property will return {}
. it is the Window object.
obj.loging() // this one will return the same as the first:
//{ name: 'boop',
// showTime: [Function: showTime],
// logger: [Function: logger],
// loging: [Function: loging] }
This is because the method logging is console logging the calling object, which is obj
.