How this Works in JavaScript: Understanding 'this' Keyword
In JavaScript,
this refers to the object that is currently executing the code. Its value depends on how a function is called, changing in methods, functions, and arrow functions.Syntax
The this keyword is used inside functions or methods to refer to the current object context. It does not have a fixed value and changes based on the call site.
function foo() { console.log(this); }-thisdepends on howfoois called.obj.method = function() { console.log(this); }-thisrefers toobjwhenmethodis called.const arrow = () => console.log(this);- arrow functions inheritthisfrom their surrounding scope.
javascript
function showThis() { console.log(this); } const obj = { method: function() { console.log(this); } }; const arrowFunc = () => { console.log(this); };
Example
This example shows how this changes depending on the call type: global function, object method, and arrow function.
javascript
function globalFunc() { console.log(this); } const obj = { name: 'MyObject', method: function() { console.log(this.name); }, arrowMethod: () => { console.log(this); } }; globalFunc(); // In browsers, logs the global object (window), or undefined in strict mode obj.method(); // Logs 'MyObject' because 'this' is obj obj.arrowMethod(); // Logs the outer 'this', usually the global object or undefined
Output
[object Window]
MyObject
[object Window]
Common Pitfalls
Many beginners expect this to always refer to the object where the function is defined, but it depends on how the function is called.
Arrow functions do not have their own this; they use this from the surrounding code, which can cause unexpected results.
javascript
const obj = { name: 'Test', regularFunc: function() { console.log(this.name); }, arrowFunc: () => { console.log(this.name); } }; obj.regularFunc(); // Correct: logs 'Test' obj.arrowFunc(); // Incorrect: logs undefined because arrowFunc's this is not obj
Output
Test
undefined
Quick Reference
| Call Type | Value of this |
|---|---|
| Global function call | Global object (window in browsers) or undefined in strict mode |
| Method call (obj.method()) | The object before the dot (obj) |
| Arrow function | Inherits from surrounding scope, no own this |
| Constructor function (called with new) | Newly created object |
| Explicit binding (call, apply, bind) | Object passed as first argument |
Key Takeaways
The value of
this depends on how a function is called, not where it is defined.In object methods,
this refers to the object owning the method.Arrow functions do not have their own
this; they use the surrounding context's this.Using
call, apply, or bind can explicitly set this.Be careful with
this in callbacks and event handlers to avoid unexpected values.