bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/JavaScript/Objects, Classes, and Advanced Patterns
JavaScript•Objects, Classes, and Advanced Patterns

The JavaScript this Keyword

What is this? When the this keyword is used in a function, it refers to an Object . Which Object , is not decided when the function is written. The value of this is decided when the function is called .

What is this?

When the this keyword is used in a function, it refers to an Object .

Which Object , is not decided when the function is written.

The value of this is decided when the function is called .

This chapter contains an advanced topic.

Make sure you understand basic JavaScript functions before continuing.

Functions are Object Methods

All JavaScript functions are object methods .

A function can be

  • A method of a JavaScript object
  • A method of the global object

this in an Object Method

When a function is an object method :

this refers to the object that owns the method.

Example

const person = {
  firstName: "John", lastName: "Doe", fullName: function() {
    return this.firstName + " " + this.lastName;
  }
};
person.fullName();

In the example above, this refers to the person object .

this.firstName means the firstName property of person .

this.firstName is the same as person.firstName .

this in a Function (Default)

By default, when this is used in a regular function, this refers to the global object .

In a browser window, the global object is [object Window] :

Example

function myFunction() {
  return this;
}

In the example above, this is the global object.

this in a Function (Strict Mode)

JavaScript strict mode does not allow default binding.

In strict mode, this used inside a function is undefined .

Example

"use strict";
function myFunction() {
  return this;
}

In the example above, this is undefined .

this Alone

When used outside a function , this always refers to the global object .

In a browser window the global object is [object Window] :

Example

let x = this;

In a regular function in strict mode , when used outside a function, this also refers to the global object :

Example

"use strict";
let x = this;

In both the examples above, this is the global object .

It is so because , this is in the global scope .

JavaScript globalThis

In JavaScript, globalThis is a special built-in object that provides a standard way to access the global object, regardless of the environment your code runs in - whether it is a browser, Node.js, a Web Worker, or another JS runtime.

  • In browsers, it is window .
  • In Node.js, it is global .
  • In Web Workers, it is self .

Each environment used to have its own name for this object. This caused compatibility issues for code meant to run everywhere.

globalThis was introduced in ECMAScript 2020 (ES11) to solve that problem. It is a unified reference to the global object, no matter the environment.

globalThis === window; // true in browsers
globalThis === global; // true in Node.js

this in Event Handlers

In HTML event handlers, this refers to the HTML element that received the event:

<button onclick="this.innerHTML='Clicked!'">Click Me</button>

this in Arrow Functions

Arrow functions do not have their own this . They inherit this from the surrounding scope.

In regular functions the this keyword represents the object that called the function, which could be the window, the document, a button or whatever.

With arrow functions the this keyword always represents the object that defined the arrow function.

What is this ?

In JavaScript, the this keyword refers to an object .

The this keyword refers to different objects depending on how it is used:

Alone, this refers to the global object .
In a function, this refers to the global object .
In a function, in strict mode, this is undefined .
In an object method, this refers to the object .
In an event, this refers to the element that received the event.
In methods like call() , apply() and bind() , this can refer to any object .

this is not a variable.

this is a keyword.

You cannot change the value of this .

This Precedence

Use the following precedence of order to determine which object this refers to:

OrderObjectBecause
1bind()this is in a function being called using bind()
2apply()this is in a function being called using apply()
2call()this is in a function being called using call()
3Object methodthis is in an object function (method)
4Global scopethis is in a function in the global scope

Examples to Understand

Below are two examples that call the same method twice:

  • When the page loads
  • When the user clicks a button

The first example uses a regular function , and the second example uses an arrow function .

The result shows that the first example returns two different objects (window and button), and the second example returns the window object twice, because the window object is the "owner" of the function.

Examples

// Regular Function: hello = function() { document.getElementById("demo").innerHTML += this;
}
// The window object calls the function: window.addEventListener("load", hello); // A button object calls the function: document.getElementById("btn").addEventListener("click", hello);

Arrow Functions in Methods

With arrow functions there are no binding of this .

They are not well suited for defining object methods .

Example

const person = {
  firstName: "John", sayHello: () => {
    return this.firstName;
  }
};
person.sayHello();

The example above does not work as expected because this does not refer to the person object .

Arrow functions can be useful inside methods when you want to keep the same this value.

Example

const person = {
 firstName: "John",
 sayHello: function() {
 return () => this.firstName;
 }
};
let hello = person.sayHello();
hello();

Common Mistakes

  • Arrow Functions as Object Methods Arrow functions do not bind their own this .
  • Assuming this Refers to an Object The value of this depends on how the function is called.
  • Forgetting Strict Mode Behavior In strict mode, this can be undefined .

What's Next?

Now you understand how this works naturally.

Are you ready to learn how to control it manually?

The JavaScript call() Function

The JavaScript apply() Function

The JavaScript bind() Function

Previous

JavaScript Generators

Next

JavaScript this Keyword

This chapter

Overview
123

Lessons

539m

Read time

1. JavaScript Objects2. JavaScript Temporal Tutorial3. JavaScript Loops4. JavaScript Advanced Functions5. JavaScript Objects6. JavaScript Temporal Intro7. JavaScript Iterables8. JavaScript Function Definitions9. JavaScript Object Properties10. JavaScript Temporal vs Date11. JavaScript Iterators12. JavaScript Callbacks13. JavaScript Object Methods14. JavaScript Temporal Duration15. JavaScript Generators16. The JavaScript this Keyword17. JavaScript this Keyword18. JavaScript Temporal Instant19. JavaScript Function call()20. JavaScript Display Objects21. JavaScript PlainDateTime22. JavaScript Function apply()23. JavaScript Object Constructors24. JavaScript Temporal PlainDate25. JavaScript Function bind()26. JavaScript PlainYearMonth27. Self-Invoking Functions28. JavaScript PlainMonthDay29. JavaScript Closures30. JavaScript Temporal PlainTime31. JavaScript Objects - Advanced32. JavaScript ZonedDateTime33. JavaScript Object Definitions34. JavaScript Temporal Now35. this in JavaScript Objects36. JS Temporal Arithmetic37. JavaScript Object Iterations38. JS Temporal Differences39. JavaScript Object Accessors40. JS Temporal Compare41. JavaScript Object Management42. JavaScript Temporal Conversion43. JavaScript Object Protection44. Temporal Display Formats45. JavaScript Object Prototypes46. JavaScript Temporal Mistakes47. JavaScript Classes48. Migrate from Date to Temporal49. JavaScript Class Inheritance50. Temporal Standards51. JavaScript Static Methods52. Asynchronous JavaScript53. Asynchronous Programming54. JavaScript Timeouts55. JavaScript Callbacks56. JavaScript Promises57. JavaScript async and await58. JavaScript fetch API59. Debugging Async JavaScript60. JavaScript Modules61. JavaScript Modules Export62. JavaScript Modules Import63. JS Module Namespace64. JavaScript Dynamic Modules65. JavaScript Meta Programming66. JavaScript Reflect67. JavaScript Proxy68. JavaScript Typed Arrays69. Typed Array Methods70. JavaScript ArrayBuffer71. JavaScript DataView72. JavaScript Atomics73. JavaScript HTML DOM Navigation74. JavaScript HTML DOM Elements (Nodes)75. JavaScript HTML DOM Collections76. JavaScript HTML DOM Node Lists77. JavaScript Window - The Browser Object Model78. JavaScript Window Screen79. JavaScript Window Location80. JavaScript Window History81. JavaScript Window Navigator82. JavaScript Popup Boxes83. JavaScript Timing Events84. JavaScript Cookies85. Web APIs - Introduction86. JavaScript Fetch API87. Web Geolocation API88. Web History API89. Pointer Events API90. Web Storage API91. JavaScript Validation API92. Web Workers API93. AJAX Introduction94. AJAX - The XMLHttpRequest Object95. AJAX - XMLHttpRequest96. AJAX - Server Response97. AJAX XML Example98. AJAX PHP Example99. AJAX ASP Example100. AJAX Database Example101. XML Applications102. JavaScript JSON103. JSON Syntax104. JSON vs XML105. JSON Data Types106. JSON.parse()107. JSON.stringify()108. JSON Object Literals109. JSON Array Literals110. JSON PHP111. JSON HTML112. JSONP113. JavaScript / jQuery DOM Selectors114. JavaScript / jQuery HTML Elements115. JavaScript / jQuery CSS Styles116. JavaScript / jQuery HTML DOM117. JavaScript Graphics118. HTML Canvas119. Plotly.js120. Chart.js121. Google Chart122. D3.js123. JavaScript Interview Preparation

On this page

What is this?Functions are Object Methodsthis in an Object Methodthis in a Function (Default)this in a Function (Strict Mode)this AloneJavaScript globalThisthis in Event Handlersthis in Arrow FunctionsWhat is this ?This PrecedenceExamples to UnderstandArrow Functions in MethodsCommon MistakesWhat's Next?