Day 11: This
Dharan Ganesan
Posted on July 24, 2023
What is this
?
In JavaScript, this
is a special keyword that refers to the context in which a function is executed. The value of this
is determined dynamically based on how a function is called, rather than how it is defined. The context can be the global object, the object that owns the method being invoked, or even explicitly set using call
, apply
, or bind
.
Understanding this
in Different Contexts:
Global Context:
When this
is referenced in the global scope (outside any function or object), it refers to the global object. In browsers, the global object is the window
object.
console.log(this === window); // Output: true
Function Context:
When this
is used within a regular function, its value depends on how the function is called.
function sayHello() {
console.log(this);
}
sayHello(); // Output: window (in non-strict mode), undefined (in strict mode)
Method Context:
When this
is used inside an object's method, it refers to the object itself.
const person = {
name: 'John',
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
person.greet(); // Output: Hello, my name is John
Strict Mode:
In JavaScript strict mode, the value of this
is not automatically coerced to the global object when calling a function in the global scope. Instead, it remains undefined
.
'use strict';
function showThis() {
console.log(this);
}
showThis(); // Output: undefined
Arrow Functions:
Arrow functions do not have their own this
binding. Instead, they inherit the this
value from the surrounding lexical scope. This behavior makes arrow functions particularly useful in callback functions or when you want to preserve the this
context.
const person = {
name: 'Alice',
greet: function() {
const innerFunc = () => {
console.log(`Hello, I'm ${this.name}`);
};
innerFunc();
}
};
person.greet(); // Output: Hello, I'm Alice
Summary
- Global Context: this refers to the
global
object. - Function Context: this refers to the
global
object in non-strict mode. In strict mode, it isundefined
. - Method Context: this refers to the
object
the method is called on. - Arrow Functions: this is inherited from the
surrounding context
and is not bound to the function.
Posted on July 24, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.