I know there are a ton of blogs and examples out there explaining the concept of this
keyword in different scenarios and reading more and more is making it confusing for me.
In the below example, the output for both the setTimeout
calls is same but I am sure not for the same reason
function x() {
setTimeout(() => {
console.log(this)
}, 100);
setTimeout(function() {
console.log(this)
}, 200);
}
x(); //logs window object twice
I know that
- The arrow functions inherit lexical scope i.e. the scope at which the parent object is defined
- The regular function gets its scope from the scope where it is called and not where it is defined.
- The context in which
setTimeout()
function runs is always window.
Can you please explain why both are logging the window
object and correct me if my understanding is wrong.