Understanding the dynamic nature of the ‘this’ keyword in JavaScript
Alamin Shaikh
Developer/Maker. Building software for everyone. Recently launched ???? devcoa.ch
In this article, we will analyze the dynamic behavior of the this keyword and learn what it points to when used in different scenarios. But first, let's have a high-level understanding of the concept.
Now, let's take a closer look at what the this keyword points to in various scenarios.
In the global scope
The this keyword, when used in the global scope, points to the global Window object. For example, console.log(this) at the top level of your script will point to the global Window object.
In a regular function
When using JavaScript in strict mode, console.log(this) in a function declaration or expression results in undefined.
'use strict'
function calc() {
console.log(this); // undefined
}
However, when using JavaScript without strict mode, console.log(this) points to the global Window object.
function calc() {
console.log(this); // Window
}
Are you enjoying the content? Read the rest of the article here.