Open In App

JavaScript - Interesting Facts About 'this' keyword

Last Updated : 02 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The this keyword in JavaScript behaves differently across execution contexts and varies between strict and non-strict modes. The 'this' keyword basically refers to the objects depending on how it is used.

1. Behavior of this inside browser

In a browser, 'this' refers to the global window object in the global context or the object that owns the method being called.

Screenshot-2024-11-27-114407
In this case this is pointing to it's current executional context which is the window object

2. Behavior of this inside Node.js

In Node.js, 'this'refers to the module.export object in the global context but is undefined inside modules when using strict mode.

Javascript
//function this node.js
console.log(this)

Output
{}

3. Inside a function kept in global space

Inside a function in the global space, this refers to the global object (window in browsers, global in Node.js) in non-strict mode, but is undefined` in strict mode.

In Strict Mode

Javacript
//function strict.js

"use strict";
function a() {
	console.log(this); 
}
a();

Output
undefined

In Normal Mode

JavaScript
// non strict mode

function a(){
	console.log(this); 
}
a();

Output
<ref *1> Object [global] {
  global: [Circular *1],
  clearInterval: [Function: clearInterval],
  clearTimeout: [Function: clearTimeout],
  setInterval: [Function: setInterval],
  setTimeout: [Functio...

4. In arrow functions kept in global space

In arrow functions, this is automatically inherited from the surrounding context or the parent context. It has same behavior in strict and non strict mode.

Javascript
"use strict";
let a = () => { 
	console.log(this) 
} 

a();

Output
{}

5. In anonymous functions kept in global space

In anonymous functions 'this' refers to the global object in non strict mode and undefined in strict mode.

In Strict Mode

JavaScript
"use strict";
let a = function() { console.log(this); } a();

Output
undefined

In Normal Mode

JavaScript
//non strict mode

let a = function () { 
    console.log(this); 
}

a();

Output
<ref *1> Object [global] {
  global: [Circular *1],
  clearInterval: [Function: clearInterval],
  clearTimeout: [Function: clearTimeout],
  setInterval: [Function: setInterval],
  setTimeout: [Functio...

6. Inside a normal function kept in an object

The 'this' inside a function which is kept inside any object always points to that object because as it considers that function as its current executional context.

JavsaScript
let obj = {a : 10, b : function() { 
    console.log(this); 
}} 

obj.b();

Output
{ a: 10, b: [Function: b] }

7. Inside an arrow function in an object

Inside an arrow function in an object, this does not refer to the object but inherits this from the surrounding context where the function is defined.

JavaScript
let obj = {a : 10, b : () => {
    console.log(this); 
}}

obj.b();

Output
{}

8. Inside an arrow function kept inside a normal function

Inside an arrow function within a normal function in an object, this still inherits from the surrounding context, not the object itself.

Javacript
let obj = {
    name : "Pranjal",
    a : function() {
        let b = () => { 
            console.log(this.name); 
        } 
        b();
    }
} 
obj.a();

Output
Pranjal

9. Inside nested arrow functions in an object

In a nested arrow function, this is inherited from the outer function where the arrow function is defined. It does not change based on the inner function's context.

JavaScript
let obj = {
    name: "Pranjal",
    a: () => {
        let b = () => {
            console.log(this);
        };
        b();
    },
};
obj.a();

Output
{}

10. Inside nested normal functions in an object

Inside nested normal functions in an object, 'this' points to the global object because regular functions have their own 'this' and cannot access the value of the parent function, causing it to default to the global object.

Javascript
let obj = {
    name: "Pranjal",
    a: function () {
        let b = function () {
            console.log(this);
        };
        b();
    },
};
obj.a();

Output
<ref *1> Object [global] {
  global: [Circular *1],
  clearInterval: [Function: clearInterval],
  clearTimeout: [Function: clearTimeout],
  setInterval: [Function: setInterval],
  setTimeout: [Functio...

11. Behavior of 'this' in call

In call(), this is set to the object reference you pass as the first argument, allowing the function to use that object's properties.

JavaScript
let obj = {
    name: "GEEKS FOR GEEKS",
};
function print(greet) {
    console.log(`${greet} Welcome to ${this.name}`);
}
print.call(obj, "Hello");

Output
Hello Welcome to GEEKS FOR GEEKS

12. Behavior of 'this' in Apply

In apply(), 'this' is set to the first argument (an object), and the second argument is an array of values for the function. In apply() we have to pass arguments to the function as a list.

JavaScript
let obj = {
    name: "GEEKS FOR GEEKS"
}
function print(greet) {
    console.log(`${greet} Welcome to ${this.name}`);
}
print.apply(obj, ["Hello"]);

Output
Hello Welcome to GEEKS FOR GEEKS

13. Behavior of this in bind

In bind(), this is set to the object you pass, and it returns a new function that you must call to use the bound 'this'.

JavaScript
let obj = {
    name: "GEEKS FOR GEEKS"
}
function print(greet) {
    console.log(`${greet} Welcome to ${this.name}`);
}
let result = print.bind(obj, "Hello");
result();

Output
Hello Welcome to GEEKS FOR GEEKS

14. Behavior of this inside DOM element

Inside the DOM element the this point to the current element in which it is placed

HTML
<html>

<body>
    <button onclick="alert(this.tagName)">Click me</button>
</body>

</html>

Output

article
inside DOM this refers to the current element in which it is kept

15. Behavior of this inside a class

'this' inside a class refers to the current instance of that class and it can access the properties present in that instance.

JavaScript
class Gfg{
    constructor(name){
        this.name=name;
    }
    greet(){
    console.log(`Welcome to ${this.name}`);
    }
}

let a=new Gfg("GEEKS FOR GEEKS");
a.greet();

Output
Welcome to GEEKS FOR GEEKS

16. In an arrow function method of class

Arrow functions inside methods inherit this from the class.

JavaScript
class Gfg{
    constructor(name){
        this.name=name;
    }
    print(){
    let show=()=>{
        console.log(`Welcome to ${this.name}`);
    }
    show();
    }
}

const a=new Gfg("GEEKS FOR GEEKS");
a.print();

Output
Welcome to GEEKS FOR GEEKS

17. In Event Handlers or Callbacks

If you use a regular function in event handlers or callbacks, 'this' might lose its reference to the class instance. You can bind it to the instance using bind(), or use arrow functions to keep the correct this.

JavaScript
//this in callbacks and eventlistners
class play{
    constructor(label)
    {
        this.label=label;
        this.handle=this.handle.bind(this);
    }
    handle(){
        console.log(`${this.label}`)
    }
}

const a=new play("Cricket");
a.handle();

Output
Cricket

Next Article

Similar Reads