Mastering This, Bind, Call, and Apply in JavaScript
How does “this” work in JavaScript and how can it be used in various contexts? We’ll show you and also explain how to use “bind,” “call,” and “apply” to maintain control over “this” in your JavaScript functions.
The “this” keyword is a fundamental concept in JavaScript that can often be confusing. We’ll show you how the “this” keyword in JavaScript works in different contexts and explain how “this” can refer to global, object-related, and constructed contexts.
In addition, discover the use of “bind,” “call,” and “apply” to explicitly control “this” and ensure that your JavaScript functions work correctly.
The this Keyword
In JavaScript, “this” refers to an object, and depending on how and where it is called, it can refer to different objects. Let’s look at various contexts:
Global Context
In the global context, “this” refers to the global object, which is “window” in a browser and “global” in Node.js.
console.log(this);
Output (in a browser):
Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
Method in an Object
When a function is a method of an object, “this” refers to that object.
const car = {
brand: 'BMW',
model: 'X5',
introduce: function() {
console.log(`I drive a ${this.brand} ${this.model}.`);
}
}
car.introduce();
Output:
I drive a BMW X5.
Constructor Function
When you use a function as a constructor to create objects, “this” refers to the newly created object.
function Person(name, age) {
this.name = name;
this.age = age;
}
const alice = new Person('Alice', 30);
console.log(alice.name); // Output: Alice
DOM Event Handler
In a DOM event handler, “this” refers to the element to which the event handler was applied.
const button = document.getElementById('myButton');
button.addEventListener('click', function() {
console.log(this.textContent);
});
When the button is clicked, the event handler outputs the button’s text.
The Methods “bind,” “call,” and “apply”
The “bind” Method
The “bind” method allows you to bind a function to a specific object. The original function remains unchanged, but when the bound function is called, “this” is set to the specified object.
const dog = {
name: 'Rex',
bark: function() {
console.log(`${this.name} barks.`);
}
}
const barking = dog.bark.bind(dog);
barking(); // Output: Rex barks.
The “call” and “apply” Methods
The “call” and “apply” methods allow you to call a function and explicitly set the value of “this” as well as pass arguments. The difference between the two methods is how you pass arguments:
- “call” expects arguments to be passed individually.
- “apply” expects arguments to be passed in an array.
function greet(greeting, punctuation) {
console.log(`${greeting}, ${this.name}${punctuation}`);
}
const person = { name: 'John' };
greet.call(person, 'Hello', '!'); // Output: Hello, John!
greet.apply(person, ['Hello', '!']); // Output: Hello, John!
Conclusion
In JavaScript, understanding “this” and using the methods “bind,” “call,” and “apply” is crucial to control the context and execution of functions. With this knowledge, you can ensure that your functions access the correct objects and execute correctly – Mastering This, Bind, Call, and Apply