Understanding the dynamic nature of the ‘this’ keyword in JavaScript

Understanding the dynamic nature of the ‘this’ keyword in JavaScript

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.

  • Each execution context has its own this keyword.
  • It never points to the function in which it is used.
  • It behaves slightly differently in strict and non-strict modes, as well as in the browser and Node.js environments.

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.

要查看或添加评论,请登录

Alamin Shaikh的更多文章

社区洞察

其他会员也浏览了