Tutorials  /  JavaScript

Mastering This, Bind, Call, and Apply in JavaScript

Ccentron Redaktion · November 2023 ·4 min read ·JavaScript, Tutorial

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.

JavaScript
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.

JavaScript
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.

JavaScript
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.

JavaScript
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.

VM

Matching infrastructure at centron

Node applications need somewhere to run: ccloud³ VMs with full root access from €3.12 per month – or as a managed server if you would rather not run it yourself. Rent a cloud server →

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.

JavaScript
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.
JavaScript
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

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie JavaScript
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren