Visit our official platform: Navvan
Follow us on: LinkedIn | YouTube
1. Function Context ๐ญ
When a regular function is invoked, the value of this
depends on how the function is called. Let's explore different scenarios: ๐ต๏ธโโ๏ธ
1.1. Method Invocation ๐จ
When a function is called as a method of an object, this
refers to the object itself. ๐ฏ
const person = {
name: 'Alice',
greet() {
console.log(`Hello, my name is ${this.name}! ๐`);
},
};
person.greet(); // Output: Hello, my name is Alice! ๐
In the example above, this
inside the greet
method refers to the person
object. ๐ค
1.2. Function Invocation ๐
When a function is invoked without an object reference, this
refers to the global object (window
in browsers, global
in Node.js) in non-strict mode, or undefined
in strict mode. ๐
function sayHello() {
console.log(`Hello, ${this}! ๐`);
}
sayHello(); // Output: Hello, [object Window]! ๐ (in a browser)
1.3. Constructor Invocation ๐๏ธ
When a function is invoked with the new
keyword, a new object is created, and this
refers to that newly created object. ๐
function Person(name) {
this.name = name;
}
const alice = new Person('Alice');
console.log(alice.name); // Output: Alice ๐
1.4. Explicit Binding ๐
You can explicitly set the value of this
using the call()
, apply()
, or bind()
methods. ๐ฏ
function greet() {
console.log(`Hello, my name is ${this.name}! ๐`);
}
const person = { name: 'Alice' };
greet.call(person); // Output: Hello, my name is Alice! ๐
greet.apply(person); // Output: Hello, my name is Alice! ๐
const boundGreet = greet.bind(person);
boundGreet(); // Output: Hello, my name is Alice! ๐
2. Arrow Functions ๐น
Arrow functions do not have their own this
binding. Instead, they inherit this
from the parent (surrounding) scope. ๐จโ๐ฉโ๐งโ๐ฆ
const person = {
name: 'Alice',
greet() {
const innerArrow = () => {
console.log(`Hello, my name is ${this.name}! ๐`);
};
innerArrow();
},
};
person.greet(); // Output: Hello, my name is Alice! ๐
In the example above, the arrow function innerArrow
inherits this
from the surrounding greet
method. ๐ช
3. Class Context ๐
In ES6 classes, this
behaves differently in constructor functions, instance methods, and static methods. ๐ซ
3.1. Constructor Functions ๐ง
In a class constructor, this
refers to the newly created instance of the class. ๐
class Person {
constructor(name) {
this.name = name;
}
}
const alice = new Person('Alice');
console.log(alice.name); // Output: Alice ๐
โ ๏ธ However, there's an interesting twist! If the constructor function returns another non-primitive value (like an object), the this
binding is discarded, and the returned value becomes the result of the new
expression. ๐ฎ
function Car(model) {
this.model = model;
return { year: 2023 };
}
let myCar = new Car("Tesla");
console.log(myCar.model); // Output: undefined
console.log(myCar.year); // Output: 2023
3.2. Instance Methods ๐ญ
In an instance method, this
refers to the instance of the class on which the method is called.
3.3. Static Methods ๐
In a static method, this
refers to the class itself, not an instance of the class. ๐
class Animal {
makeSound() {
console.log(this); // `this` refers to the instance
}
static getSpecies() {
console.log(this); // `this` refers to the class
}
}
const dog = new Animal();
dog.makeSound(); // Output: instance of Animal
Animal.getSpecies(); // Output: Animal
๐ In derived classes, constructors have slightly different behavior. Unlike base class constructors, derived constructors have no initial this
binding. Calling super()
creates the this
binding within the constructor.
๐จ It's important to remember that referring to this
before calling super()
will throw an error. ๐จ
class Vehicle {}
class Car extends Vehicle {
constructor() {
super(); // Creates `this` binding
console.log(this); // Now, `this` is available
}
}
new Car();
4. Global Context ๐
In the global execution context, this
refers to the global object (window
in browsers, global
in Node.js). ๐
console.log(this === window); // Output: true ๐ (in a browser)
5. Event Handlers ๐
When a function is used as an event handler, this
refers to the element that triggered the event. ๐ฏ
<button id="myButton">Click me! ๐ฑ๏ธ</button>
const button = document.getElementById('myButton');
button.addEventListener('click', function () {
console.log(this === button); // Output: true ๐
});
In the example above, this
inside the event handler function refers to the button element. ๐
6. Strict Mode ๐จ
In strict mode, the value of this
remains whatever it was set to when entering the execution context. If this
is not defined, it remains undefined
. ๐ค
function strictFunc() {
return this;
}
console.log(strictFunc() === undefined); // Output: true ๐
Conclusion ๐
Phew! We've covered some ground in this little dive into the context of this
in JavaScript. From normal to arrow functions, classes to event handlers, and strict mode considerations, this
plays a crucial role in understanding how JS code behaves. ๐
Remember, the value of this
is determined by how a function is called, not where it's defined. ๐ช
If you enjoyed this article, please make sure to Subscribe, Like, Comment, and Connect with us today! ๐
Visit our official platform: Navvan
Top comments (0)