1. This in Global Space#
- In the global context,
this
refers to the global object.- Browser:
window
- Node.js:
global
console.log(this); // In a browser, logs the Window object
2. This Inside a Function#
- In a regular function,
this
refers to the global object when called globally. - When called as a method of an object,
this
refers to that object.
function regularFunction() {
console.log(this); // Logs global object
}
regularFunction();
const obj = {
method: function () {
console.log(this); // Logs the obj
},
};
obj.method();
3. This in Strict Mode#
- In strict mode (
'use strict';
), this
is undefined
if not set by the call site.
"use strict";
function strictFunction() {
console.log(this); // undefined
}
strictFunction();
4. This Value Depends on Call Context#
- Global Context:
this
is the global object. - Object Method:
this
is the object the method is called on. - Constructor: When using
new
, this
refers to the new object created.
function Constructor() {
console.log(this); // Logs a new object when invoked with `new`
}
new Constructor();
5. This Inside an Object’s Method#
this
refers to the object itself within its method.
const car = {
brand: "Toyota",
getBrand: function () {
console.log(this.brand); // Logs "Toyota"
},
};
car.getBrand();
6. Call, Apply, and Bind Methods#
call()
: Invokes a function with a specified this
value.apply()
: Similar to call()
, but takes an array of arguments.bind()
: Returns a new function with a specified this
value.
function greet() {
console.log(this.name);
}
const person = { name: "Alice" };
greet.call(person); // Output: "Alice"
7. This Inside Arrow Functions#
- Arrow functions lexically bind
this
, meaning they inherit it from the surrounding scope.
const obj2 = {
value: 42,
arrowFunction: () => {
console.log(this.value); // Inherits from global scope
},
};
obj2.arrowFunction(); // Output: undefined
8. This Inside DOM Event Handlers#
- In event handlers,
this
refers to the element that fired the event.
<button id="myButton">Click me</button>
<script>
document.getElementById("myButton").addEventListener("click", function () {
console.log(this); // Logs the button element
});
</script>