JS This Binding Call Apply Bind
Ringkasan
this di JS ditentukan oleh cara fungsi dipanggil, bukan di mana ia ditulis. call/apply/bind mengikat secara eksplisit.
Konsep Dasar
- Method call:
obj.fn()→this=obj. - Function call biasa:
this=undefined(strict) atau global. fn.call(ctx, a, b),fn.apply(ctx, [a,b]),fn.bind(ctx)(returns new fn).- Arrow function tidak punya
thissendiri — menangkap dari enclosing.
Cara Kerja / Struktur
function who(){ return this.name; }
const a = {name:"A"}; const b = {name:"B"};
who.call(a); // "A"
who.apply(b); // "B"
const bound = who.bind(a); bound(); // "A"Catatan Implementasi
- Event handler sering butuh
bindatau arrow agarthisbenar. - Arrow function di method class cocok untuk callback (menangkap instance).
Kesalahan Umum
thisundefined di callback function biasa → pakai arrow ataubind.- Lupa
applypakai array,callpakai argumen terpisah.
Glosarium
- Implicit binding: this dari objek pemanggil.
- Hard binding: bind eksplisit via bind().