Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript this Keyword
Next article icon

JavaScript - Interesting Facts About 'this' keyword

Last Updated : 23 Jul, 2025
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
JavaScript this Keyword

P

pranjalonj7
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Misc
  • JavaScript Facts

Similar Reads

    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
    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
    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 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
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • DSA Tutorial
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences