BAB 23 — This Binding: Memahami Konteks Eksekusi di JavaScript

BAB 23 — This Binding: Memahami Konteks Eksekusi di JavaScript

Keyword this adalah salah satu konsep paling penting dan sering membingungkan di JavaScript. this menunjuk pada konteks eksekusi dari sebuah fungsi atau objek, dan nilainya berubah tergantung cara fungsi dipanggil.

Memahami this membantu menulis kode lebih predictable, modular, dan bebas bug.


1. this pada Global

  • Di global scope (browser), this menunjuk ke global object (window).
  • Di strict mode → this adalah undefined.
console.log(this); // window (browser)
"use strict";
console.log(this); // undefined

Insight:

  • Jangan mengandalkan this di global untuk menyimpan data → gunakan const/let.

2. this pada Method

  • Saat fungsi dipanggil sebagai method objek, this menunjuk pada objek pemanggil.
const person = {
    name: "Alice",
    greet() {
        console.log(`Hello, nama saya ${this.name}`);
    }
};

person.greet(); // Hello, nama saya Alice

Insight:

  • this fleksibel → tergantung cara panggilan fungsi.

3. this pada Event

  • Dalam event handler DOM, this menunjuk ke elemen yang memicu event (default behavior).
const button = document.querySelector("button");
button.addEventListener("click", function() {
    console.log(this); // button element
});
  • Namun jika menggunakan arrow function, this bersifat lexical → mengacu ke outer scope, bukan element.
button.addEventListener("click", () => {
    console.log(this); // biasanya window/global
});

Tips:

  • Gunakan function biasa jika ingin this menunjuk ke event target.
  • Gunakan arrow function jika ingin lexical this dari outer scope.

4. this pada Class

  • Di dalam class, this menunjuk pada instance objek yang dibuat oleh constructor.
class Person {
    constructor(name) {
        this.name = name;
    }
    greet() {
        console.log(`Halo, saya ${this.name}`);
    }
}

const bob = new Person("Bob");
bob.greet(); // Halo, saya Bob
  • Method class yang dipanggil dari instance → this otomatis → aman.

5. Arrow Function & Lexical this

  • Arrow function tidak memiliki this sendiri → menggunakan this dari outer scope.
class Timer {
    constructor() {
        this.seconds = 0;
    }
    start() {
        setInterval(() => {
            this.seconds++;
            console.log(this.seconds);
        }, 1000);
    }
}

const t = new Timer();
t.start(); // this → instance Timer
  • Tanpa arrow function → this di setInterval menunjuk ke window/global, bukan instance.

Insight:

  • Arrow function → solusi elegan untuk callback, asynchronous, dan DOM event handler agar this tetap konsisten.

6. Problem “Lost This”

Masalah umum: this hilang saat method dipanggil secara independen.

const person = {
    name: "Alice",
    greet() { console.log(this.name); }
};

const greetFunc = person.greet;
greetFunc(); // undefined (this lost)

Solusi:

  1. Bind
const boundGreet = person.greet.bind(person);
boundGreet(); // Alice
  1. Call / Apply
person.greet.call(person);  // Alice
person.greet.apply(person); // Alice
  1. Arrow function
const obj = {
    name: "Bob",
    greet: () => console.log(this.name)
};
  • Gunakan arrow function untuk lexical this, tapi hati-hati → tidak cocok untuk method objek yang perlu this objek.

7. Praktik Terbaik this

  1. Gunakan arrow function untuk callback agar lexical this tetap terjaga.
  2. Gunakan bind jika ingin method tetap terkait objek saat dipassing sebagai callback.
  3. Di class, metode instance → this aman menunjuk instance.
  4. Hindari menyimpan this ke variabel global → gunakan let/const atau arrow function.
  5. Pahami cara pemanggilan fungsi: method, global, constructor, event, call/apply/bind.

8. Kesimpulan

  • this → menunjuk konteks eksekusi, nilainya berbeda tergantung cara fungsi dipanggil.
  • Global → window/global, strict mode → undefined.
  • Method → objek pemanggil.
  • Event → elemen yang memicu event (kecuali arrow function).
  • Class → instance objek.
  • Arrow function → lexical this → ambil dari outer scope.
  • Lost this → bisa diatasi dengan bind, call, apply, atau arrow function.

💡 Insight: Memahami this adalah kunci debugging, class design, event handling, dan asynchronous callback di JavaScript modern.