JavaScript - Interesting Facts About 'this' keyword
Last Updated :
02 Dec, 2024
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.
In this case this is pointing to it's current executional context which is the window object2. 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)
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();
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();
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();
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();
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();
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();
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");
OutputHello 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"]);
OutputHello 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();
OutputHello 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
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();
OutputWelcome 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();
OutputWelcome 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();
Similar Reads
Interesting Facts About JavaScript
JavaScript (often abbreviated as JS) is one of the most popular programming languages in the world. It is an interpreted, high-level programming language that follows ECMAScript. It powers interactive websites and is packed with amazing features that make it special and powerful. Interesting Facts A
5 min read
JavaScript this Keyword
The 'this keyword' in JavaScript refers to the object to which it belongs. Its value is determined by how a function is called, making it a dynamic reference. The 'this' keyword is a powerful and fundamental concept used to access properties and methods of an object, allowing for more flexible and r
4 min read
What does "this" keyword mean in JavaScript ?
In JavaScript, the 'this' keyword stands as a identifier, bridging the gap between functions and their invoking context. This unique identifier grants functions the ability to interact with and manipulate the properties of the object that triggered their invocation, serving as a reference to the cur
2 min read
JavaScript Interview Questions and Answers
JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
What is the new keyword in JavaScript ?
In this article, we will understand exactly what the new keyword is, and why we use the new keyword, and how we can use the new keyword. The new keyword in JavaScript: The new keyword is used to create an instance of a user-defined object type and a constructor function. It is used to construct and
2 min read
JavaScript this Identifier
In JavaScript, 'this' identifier can be used in different contexts and scopes. Let us go through each to determine what this is and how it is decided. Global Scope: Whenever 'this' keyword is used in the global context i.e. not as a member of a function or object declaration, it always refers to the
4 min read
JavaScript this Operator Interview Questions
In JavaScript, this is a special keyword that refers to the current object or context. It behaves differently depending on where it's used. If you use this in a regular function, it refers to the global object (in browsers, this is the window). In an object's method, this refers to the object itself
9 min read
Classes and Objects in JavaScript
Classes Classes were first introduced in the new version of the ES6 classes which replaced the previously used functions. Class is nothing but a blueprint for an object of it. It is used to create an object mainly. If we relate it to a real-life example then it is like a plan for a building or house
4 min read
JavaScript Object defineProperties() Method
The Object.defineProperties() method in JavaScript is a standard built-in Object that defines a new or modifies existing properties directly on an object and it returns the object.Syntax:Object.defineProperties(obj, props) Parameters:Obj: This parameter holds the object on which the properties are g
2 min read
What is the (function() { } )() construct in JavaScript?
If you've ever played around with JavaScript, you might have seen this expression. It's like a strange set of symbols, but it has a special name that is an immediately invoked function expression, or IIFE. In this article, we will understand each element of the expression as well as the functionalit
3 min read