The this
keyword in JavaScript refers to the object that is executing the current function. Its value depends on how and where the function is called.
Key Rules for this
in Different Contexts:
1. Global Context:
In the global scope or outside any function:
- In browser environments,
this
refers to thewindow
object. - In strict mode (
'use strict'
),this
isundefined
.
javascriptCopyEditconsole.log(this); // Window (in browsers)
2. Inside a Function (Non-Strict Mode):
- If a function is called in the global context,
this
refers to thewindow
object.
javascriptCopyEditfunction show() {
console.log(this);
}
show(); // Window
- In strict mode:
javascriptCopyEdit'use strict';
function show() {
console.log(this);
}
show(); // undefined
3. Inside an Object Method:
- When a function is called as a method of an object,
this
refers to the object.
javascriptCopyEditconst user = {
name: 'John',
greet: function() {
console.log(this.name); // Refers to `user` object
}
};
user.greet(); // 'John'
4. Inside an Arrow Function:
- Arrow functions do not have their own
this
. this
is lexically inherited from the surrounding scope.
javascriptCopyEditconst user = {
name: 'John',
greet: () => {
console.log(this.name); // `this` refers to the outer scope (e.g., `window` in global)
}
};
user.greet(); // undefined (or `window.name` in browsers)
Another example (lexical this
):
javascriptCopyEditconst user = {
name: 'John',
greet: function() {
const arrowFunc = () => {
console.log(this.name);
};
arrowFunc();
}
};
user.greet(); // 'John' because arrow function inherits `this` from `greet()`
5. In Event Listeners:
- In a DOM event listener,
this
refers to the HTML element that received the event.
javascriptCopyEditdocument.querySelector('button').addEventListener('click', function() {
console.log(this); // The button element
});
6. With call()
, apply()
, and bind()
:
These methods allow you to manually set this
.
call()
– Immediately invokes a function with a specifiedthis
value.apply()
– Same ascall()
, but arguments are passed as an array.bind()
– Returns a new function withthis
permanently set.
javascriptCopyEditfunction show() {
console.log(this.name);
}
const user = { name: 'John' };
show.call(user); // 'John'
show.apply(user); // 'John'
const boundShow = show.bind(user);
boundShow(); // 'John'
Summary Table:
Context | this Value |
---|---|
Global Scope | window (or global in Node.js), undefined in strict mode |
Function (non-strict) | window |
Function (strict mode) | undefined |
Object Method | The object that the method is called on |
Arrow Function | Inherits this from surrounding scope |
Event Listener | The element that received the event |
call() , apply() , bind() | Set explicitly by the method |
Understanding this
is fundamental to mastering JavaScript, especially when working with objects, classes, and event handling.