Masukkan Password
53 Function & this Variable
Lecture ini adalah lanjutan langsung dari lecture sebelumnya tentang this. Kalau sebelumnya kita baru belajar:
object.method()→thismenunjuk ke object yang memanggil method.
Sekarang cakupannya diperluas. Kita akan melihat apa isi this ketika digunakan di beberapa situasi berbeda.
Ada 5 situasi utama yang perlu kamu pahami:
1. Global scope
2. Regular function
3. Method pada object
4. Arrow function
5. Event handler
Dan yang paling penting untuk lecture ini adalah memahami perbedaan:
Regular function mendapatkan
thissendiri, sedangkan arrow function tidak memilikithissendiri.
1. Ingat Lagi: Apa Itu this?
this adalah keyword khusus JavaScript yang nilainya ditentukan berdasarkan konteks/cara function digunakan atau dipanggil.
Jangan menganggap:
this
selalu berarti:
object
Karena nilainya bisa berbeda tergantung situasinya.
Misalnya:
person.calculateAge();
Di dalam method:
this
mengarah ke:
person
Tetapi kalau kita menggunakan this di global scope, hasilnya berbeda.
Kalau di regular function, bisa berbeda lagi.
Kalau di arrow function, ada aturan lain lagi.
2. Peta Besar this
Untuk konteks lecture ini, kamu bisa membuat tabel mental seperti ini:
Tempat this digunakan | Nilai this |
|---|---|
| Global scope di browser | window |
| Regular function, non-strict | window |
| Regular function, strict mode | undefined |
Method object.method() | object yang memanggil |
| Arrow function | this dari outer/parent scope |
| Event handler regular function | element DOM yang menerima event |
Catatan: ini adalah aturan yang disederhanakan untuk konteks lecture. Nanti ada beberapa detail tambahan tentang this seperti call(), bind(), constructor, class, dan module.
Sekarang kita bedah satu per satu.
3. this di Global Scope
Pertama:
console.log(this);
Kalau kode tersebut berada di global scope browser, maka:
this
mengarah ke:
window
Jadi:
console.log(this);
kurang lebih menghasilkan:
console.log(window);
4. Apa Itu window?
Karena kita sedang bekerja di browser, JavaScript memiliki sebuah global object bernama:
window
window merepresentasikan environment/browser window tempat halaman web berjalan.
Contohnya:
window.alert("Hello");
Kita biasanya cukup menulis:
alert("Hello");
Browser menyediakan banyak hal melalui window.
Misalnya:
window.document
window.console
window.setTimeout
window.location
dan sebagainya.
Jadi secara mental:
Browser
↓
window
↓
global object
Untuk browser:
this === window
di global scope tertentu.
5. Global Scope vs Function Scope
Ini perlu dibedakan.
Misalnya:
console.log(this);
berada langsung di global scope.
GLOBAL
↓
this
↓
window
Tetapi kalau:
function greet() {
console.log(this);
}
this sekarang berada di dalam function.
Maka kita perlu melihat jenis function dan cara pemanggilannya.
6. this di Regular Function
Misalnya:
function greet() {
console.log(this);
}
greet();
Ini adalah regular function.
Perhatikan cara memanggilnya:
greet();
Bukan:
person.greet();
Jadi ini adalah regular function call.
Dalam non-strict mode, lecture mengajarkan:
greet()
↓
regular function
↓
non-strict mode
↓
this = window
Jadi:
function greet() {
console.log(this);
}
greet();
akan menghasilkan window di browser non-strict.
7. Kenapa Bisa window?
Ini salah satu aturan JavaScript untuk regular function dalam non-strict mode.
Ketika function dipanggil seperti:
greet();
tidak ada object tertentu yang menjadi pemanggil.
Jadi dalam non-strict mode, this default-nya adalah global object.
Di browser:
global object
↓
window
Sehingga:
this === window
8. Strict Mode Mengubah Perilaku
Sekarang kita menggunakan:
"use strict";
Contoh:
"use strict";
function greet() {
console.log(this);
}
greet();
Sekarang:
this
adalah:
undefined
Jadi:
Regular function
↓
greet()
↓
strict mode
↓
this = undefined
9. Kenapa Strict Mode Penting?
Strict mode membuat JavaScript lebih ketat terhadap beberapa perilaku yang dianggap berpotensi membingungkan.
Untuk this, perbedaannya sangat jelas:
Non-strict
function greet() {
console.log(this);
}
greet();
→ browser:
window
Strict
"use strict";
function greet() {
console.log(this);
}
greet();
→
undefined
Jadi jangan hanya menghafal:
“
thisdi function = window.”
Itu tidak selalu benar.
Lebih tepat:
Regular function yang dipanggil secara biasa (
greet()) menghasilkanthis = windowdalam non-strict mode, danthis = undefineddalam strict mode.
10. Function Expression Bagaimana?
Sama saja.
Misalnya:
const greet = function () {
console.log(this);
};
greet();
Ini adalah function expression, tetapi function tersebut tetap merupakan regular function.
Jadi dalam non-strict mode:
greet()
↓
regular function
↓
this = window
Dalam strict mode:
greet()
↓
regular function
↓
this = undefined
Jadi:
Function expression tidak otomatis berarti arrow function.
Ini dua hal yang berbeda.
11. Regular Function vs Function Expression
Ini penting supaya tidak tertukar.
Function declaration
function greet() {
console.log(this);
}
Function expression
const greet = function () {
console.log(this);
};
Keduanya menggunakan:
regular function
Yang berbeda adalah cara function dibuat/didefinisikan.
12. Sekarang Kasus yang Menarik: Function di Dalam Method
Misalnya:
const person = {
name: "John",
calculateAge: function () {
console.log("Method:", this);
function inner() {
console.log("Inner:", this);
}
inner();
}
};
Kemudian:
person.calculateAge();
Apa yang terjadi?
13. this di Method
Pertama:
person.calculateAge();
Karena calculateAge dipanggil melalui:
person
maka:
this === person
Jadi:
console.log("Method:", this);
menghasilkan object person.
person.calculateAge()
↓
this
↓
person
Sampai sini sama seperti lecture sebelumnya.
14. Tapi Bagaimana dengan inner()?
Di dalam method kita membuat:
function inner() {
console.log(this);
}
Kemudian:
inner();
Perhatikan cara pemanggilannya:
inner();
Bukan:
person.inner();
Jadi inner() adalah regular function call.
Maka JavaScript tidak berkata:
“Karena
inner()berada di dalamperson.calculateAge(), berartithisharus person.”
Tidak.
Itu adalah kesalahan pemahaman yang sering terjadi.
15. Hasilnya
Dalam non-strict mode:
person.calculateAge()
↓
this = person
↓
inner()
↓
regular function
↓
this = window
Jadi bisa terjadi:
Method:
this → person
Inner function:
this → window
Ini adalah salah satu poin paling penting dari lecture.
16. “Tapi Inner Function Berada di Dalam Method!”
Benar.
Secara struktur:
person
└── calculateAge()
└── inner()
Tetapi letak function tidak otomatis menentukan this untuk regular function.
Ini sangat penting.
Jangan berpikir:
inner function ada di person
↓
this = person
Salah.
Yang harus ditanyakan adalah:
Bagaimana
inner()dipanggil?
Jawab:
inner();
Itu regular function call.
Maka dalam non-strict:
this = window
dan strict:
this = undefined
17. Ini Berbeda dengan Scope
Nah, di sini ada konsep yang sering tertukar:
Scope
Menentukan:
Variable apa yang bisa diakses?
this
Menentukan:
Nilai
thisyang digunakan oleh function berdasarkan aturan pemanggilannya/konteksnya.
Misalnya:
const person = {
name: "John",
test: function () {
const x = 10;
function inner() {
console.log(x);
console.log(this);
}
inner();
}
};
inner() masih bisa mengakses:
x
karena masalah scope.
Tetapi this di inner() tidak otomatis menjadi person.
Jadi:
Scope
↓
aturan lexical / nested visibility
this
↓
aturan khusus function invocation
Jangan dicampur.
18. Sekarang Masuk ke Arrow Function
Nah, ini bagian yang sangat penting.
Arrow function:
const greet = () => {
console.log(this);
};
berbeda dengan regular function dalam hal this.
Arrow function tidak memiliki this sendiri.
Ini kalimat yang harus kamu hafalkan:
Arrow function does not create its own
this.
Lalu bagaimana arrow function mendapatkan this?
Jawabannya:
Arrow function menggunakan
thisdari outer/parent lexical scope-nya.
19. Apa Maksud “Parent Scope”?
Misalnya:
const greet = () => {
console.log(this);
};
Arrow function ini dibuat di global scope.
Strukturnya:
GLOBAL SCOPE
│
└── greet arrow function
Karena arrow function tidak memiliki this sendiri, dia melihat ke parent scope.
Parent-nya:
GLOBAL
Dan di browser, dalam konteks global yang digunakan lecture:
this → window
Maka arrow function juga mendapatkan nilai tersebut.
20. Visualisasi Arrow Function
GLOBAL SCOPE
│
│ this = window
↓
ARROW FUNCTION
│
│ tidak punya this sendiri
↓
ambil this dari parent
↓
window
Jadi:
const greet = () => {
console.log(this);
};
di global scope browser akan melihat this dari lingkungan luarnya.
21. Arrow Function di Dalam Method
Ini justru contoh yang paling menarik.
Misalnya:
const person = {
name: "John",
calculateAge: function () {
console.log("Method:", this);
const inner = () => {
console.log("Arrow:", this);
};
inner();
}
};
Kemudian:
person.calculateAge();
22. Apa yang Terjadi?
Pertama:
person.calculateAge();
Method dipanggil melalui person.
Maka:
this di calculateAge
↓
person
Sekarang lihat arrow function:
const inner = () => {
console.log(this);
};
Arrow function tidak membuat this sendiri.
Maka dia mengambil this dari parent scope.
Parent-nya adalah function calculateAge.
Di calculateAge:
this = person
Maka arrow function juga menggunakan:
this = person
23. Visualisasinya
person.calculateAge()
↓
calculateAge()
↓
this = person
↓
┌────────────────┐
│ const inner = │
│ () => { │
│ this │
│ } │
└────────────────┘
↓
arrow tidak punya this sendiri
↓
ambil this parent
↓
person
Jadi:
inner();
tetap mendapatkan:
this === person
karena inner adalah arrow function.
24. Bandingkan Regular vs Arrow
Ini adalah perbandingan yang sangat penting.
Misalnya:
const person = {
name: "John",
test: function () {
console.log("outer:", this);
function regular() {
console.log("regular:", this);
}
const arrow = () => {
console.log("arrow:", this);
};
regular();
arrow();
}
};
person.test();
Dalam non-strict browser:
outer:
this → person
regular:
this → window
arrow:
this → person
Kenapa?
Regular function
regular()
↓
punya this sendiri
↓
regular function call
↓
window
Arrow function
arrow()
↓
tidak punya this sendiri
↓
ambil this parent
↓
parent = test()
↓
this = person
25. Ini Alasan Arrow Function Sangat Berguna
Misalnya kita ingin menjalankan function kecil di dalam method tetapi tetap ingin menggunakan this milik method.
Dengan regular function:
const person = {
name: "John",
greet: function () {
function inner() {
console.log(this.name);
}
inner();
}
};
Dalam non-strict browser, this di inner() akan menjadi window, bukan person.
Tetapi dengan arrow:
const person = {
name: "John",
greet: function () {
const inner = () => {
console.log(this.name);
};
inner();
}
};
Arrow mengambil this dari greet().
Jadi:
greet()
↓
this = person
↓
arrow inner
↓
ambil this dari greet
↓
this = person
Ini akan sangat berguna nanti.
26. Sekarang Masuk ke Event Handler
Lecture kemudian membahas this pada event handler.
Misalnya HTML:
<button id="example-button">Click Me</button>
JavaScript:
const button = document.getElementById("example-button");
button.addEventListener("click", function () {
console.log(this);
});
Ketika button diklik:
click
↓
event handler dijalankan
↓
this
↓
button
Jadi this menunjuk ke DOM element yang menjadi target handler tersebut dalam pola regular function ini.
27. Kenapa this Menjadi Button?
Karena:
button.addEventListener("click", function () {
console.log(this);
});
Function tersebut adalah regular function yang digunakan sebagai event handler.
Browser menjalankan handler tersebut dengan konteks element terkait.
Maka:
this
mengarah ke:
button
28. Contoh Praktis
Misalnya kita ingin mengubah warna button ketika diklik:
button.addEventListener("click", function () {
this.style.backgroundColor = "red";
});
Ketika button diklik:
this
↓
button
↓
this.style
↓
button.style
Jadi kita tidak perlu menulis:
button.style.backgroundColor = "red";
kita bisa menggunakan:
this.style.backgroundColor = "red";
29. Tapi Kalau Event Handler Menggunakan Arrow Function?
Ini bagian yang sangat penting.
Kalau kita ubah:
button.addEventListener("click", function () {
console.log(this);
});
menjadi:
button.addEventListener("click", () => {
console.log(this);
});
hasilnya tidak sama.
Kenapa?
Karena arrow function:
tidak memiliki
thissendiri.
Dia akan mengambil this dari outer scope.
Kalau kode tersebut berada di global scope browser, maka parent scope-nya adalah global.
Sehingga lecture menunjukkan:
arrow function
↓
tidak punya this sendiri
↓
ambil this parent
↓
global scope
↓
window
Jadi bukan button.
30. Ini Perbandingan yang Wajib Kamu Hafalkan
Regular function sebagai event handler
button.addEventListener("click", function () {
console.log(this);
});
click
↓
regular function
↓
this = button
Arrow function sebagai event handler
button.addEventListener("click", () => {
console.log(this);
});
click
↓
arrow function
↓
tidak punya this sendiri
↓
ambil this parent
↓
bukan otomatis button
Dalam contoh lecture yang berada di global scope browser, parent this mengarah ke window.
31. Jangan Campurkan this dengan event.target
Ada satu hal yang penting untuk kamu ketahui karena nanti sering membingungkan.
Dalam event handler kita bisa memiliki:
function (event) {
console.log(this);
console.log(event.target);
}
Keduanya bisa sama, tetapi konsepnya berbeda.
this
Dalam regular event handler:
this
mengacu pada element tempat handler sedang dipasang/dijalankan dalam konteks tersebut.
event.target
event.target
adalah element yang sebenarnya menjadi target awal event.
Misalnya:
button
└── span
Kalau kamu klik span, bisa saja:
this → button
event.target → span
Ini akan sangat penting saat nanti belajar event bubbling dan event delegation.
32. Hubungkan dengan Lecture Event Bubbling
Kamu sebelumnya sudah belajar:
button
↑
div
↑
header
event bisa bubble ke atas.
Sekarang tambahkan:
this
dan:
event.target
Misalnya listener dipasang di div:
div.addEventListener("click", function (event) {
console.log(this);
console.log(event.target);
});
Kalau user klik button di dalam div:
event.target
↓
button
this
↓
div
Jadi:
event.target= tempat event awal terjadi.
Sedangkan:
thispada regular listener = element tempat listener tersebut dijalankan/attached dalam konteks ini.
Ini konsep yang bagus untuk mulai kamu simpan dari sekarang.
33. Lima Aturan Lecture Ini
Sekarang kita rangkum persis seperti yang instructor lakukan.
Rule 1 — Global Scope
console.log(this);
Di browser:
this → window
Rule 2 — Regular Function
function greet() {
console.log(this);
}
greet();
Non-strict:
this → window
Strict:
this → undefined
Rule 3 — Method Call
const person = {
name: "John",
greet: function () {
console.log(this);
}
};
person.greet();
Maka:
this → person
Karena:
person.greet()
↑
object pemanggil
Rule 4 — Arrow Function
const greet = () => {
console.log(this);
};
Arrow function:
tidak punya this sendiri
↓
mengambil this dari outer/parent scope
Rule 5 — Event Handler
Regular function:
button.addEventListener("click", function () {
console.log(this);
});
Maka:
this → button
Tetapi arrow:
button.addEventListener("click", () => {
console.log(this);
});
tidak otomatis mendapatkan:
this → button
karena arrow tidak punya this sendiri.
34. Tabel Besar untuk Dihafalkan
| Situasi | this |
|---|---|
| Global scope browser | window |
function greet() {} → greet() non-strict | window |
function greet() {} → greet() strict | undefined |
person.greet() | person |
Regular function di dalam method, dipanggil inner() | window / undefined |
| Arrow function | this dari outer scope |
| Event handler regular function | element tempat handler dipasang |
| Event handler arrow function | this dari outer scope |
35. Visualisasi Super Penting
Saya sarankan kamu simpan diagram ini:
this
│
┌────────────┼─────────────┐
↓ ↓ ↓
Global Regular Method
scope function call
↓ ↓ ↓
window window* object pemanggil
/ undefined
*
tergantung
strict mode
│
↓
Arrow function
│
↓
tidak punya this sendiri
│
↓
ambil this parent scope
│
↓
Event handler
│
↓
regular function
↓
DOM element
36. Bagian yang Paling Sering Membingungkan
“Bukankah this selalu object?”
Tidak.
Contoh:
console.log(this);
bisa:
window
Regular function strict:
"use strict";
function test() {
console.log(this);
}
bisa:
undefined
Jadi this tidak selalu object.
37. “Bukankah Function di Dalam Object Berarti this = Object?”
Tidak selalu.
Misalnya:
const person = {
test: function () {
function inner() {
console.log(this);
}
inner();
}
};
Kita menjalankan:
person.test();
this di test():
person
Tetapi this di inner():
window
dalam non-strict.
Karena:
inner();
adalah regular function call.
38. “Kalau Begitu Kenapa Arrow Berbeda?”
Karena arrow function tidak membuat this baru.
Misalnya:
const person = {
test: function () {
const inner = () => {
console.log(this);
};
inner();
}
};
Ketika:
person.test();
maka:
test()
↓
this = person
↓
inner arrow
↓
ambil this dari test()
↓
this = person
39. Hubungan dengan Lecture Arrow Function Sebelumnya
Sekarang lecture sebelumnya menjadi jauh lebih masuk akal.
Sebelumnya instructor mengatakan:
Arrow function punya beberapa perbedaan penting dengan regular function, terutama terkait
this.
Sekarang kamu tahu kenapa.
Regular function
function () {}
memiliki mekanisme this sendiri berdasarkan cara function dipanggil.
Arrow function
() => {}
tidak membuat this sendiri.
Dia mengambil this dari outer lexical scope.
40. Cara Berpikir Saat Melihat this
Jangan langsung panik ketika melihat:
this
Lakukan langkah berikut.
Langkah 1
Tanya:
thisberada di function atau global scope?
Langkah 2
Kalau berada di function:
Function ini regular atau arrow?
Langkah 3
Kalau regular function:
Bagaimana function tersebut dipanggil?
Contoh:
person.greet();
→ this = person
Sedangkan:
greet();
→ default this sesuai strict/non-strict.
Langkah 4
Kalau arrow:
Cari parent/outer scope-nya.
Karena:
arrow
↓
tidak punya this sendiri
↓
ambil this parent
41. Contoh Latihan Mental
Contoh A
console.log(this);
Browser global scope.
Jawaban:
window
Contoh B
function test() {
console.log(this);
}
test();
Non-strict browser:
window
Contoh C
const person = {
name: "John",
test: function () {
console.log(this);
}
};
person.test();
Jawaban:
person
Contoh D
const person = {
name: "John",
test: function () {
function inner() {
console.log(this);
}
inner();
}
};
person.test();
Non-strict:
window
Contoh E
const person = {
name: "John",
test: function () {
const inner = () => {
console.log(this);
};
inner();
}
};
person.test();
Jawaban:
person
Karena arrow mengambil this dari test().
Contoh F
button.addEventListener("click", function () {
console.log(this);
});
Saat button diklik:
button
Contoh G
button.addEventListener("click", () => {
console.log(this);
});
Tidak otomatis:
button
Arrow mengambil this dari outer scope.
42. Satu Diagram untuk Memahami Regular vs Arrow
Ini mungkin diagram paling penting dari lecture:
REGULAR FUNCTION
────────────────────────────
function inner() {
console.log(this);
}
↓
punya this sendiri
↓
tentukan berdasarkan cara dipanggil
ARROW FUNCTION
────────────────────────────
const inner = () => {
console.log(this);
};
↓
tidak punya this sendiri
↓
ambil this dari parent scope
43. Catatan Teknis Penting
Ada sedikit penyederhanaan dalam lecture yang perlu kamu ketahui supaya tidak salah memahami konsep JavaScript secara keseluruhan.
Lecture mengatakan:
“Regular function akan selalu
window.”
Lebih tepatnya:
regular function + plain call
dalam non-strict mode:
fn();
→ this menjadi global object.
Dalam strict mode:
"use strict";
fn();
→ undefined.
Tetapi regular function yang dipanggil sebagai:
person.fn();
memiliki this yang berbeda:
this → person
Jadi jenis function saja belum cukup untuk menentukan this.
Kita juga harus melihat cara function dipanggil.
44. Cheat Sheet Final
┌──────────────────────────────────────┐
│ THIS KEYWORD │
└──────────────────────────────────────┘
1. GLOBAL
this → window (browser)
2. REGULAR FUNCTION
fn()
↓
non-strict → window
strict → undefined
3. METHOD
person.fn()
↓
this → person
4. ARROW FUNCTION
() => {}
↓
tidak punya this sendiri
↓
ambil this dari parent scope
5. EVENT HANDLER
element.addEventListener(
"click",
function () {}
)
↓
this → element
Jika menggunakan arrow:
() => {}
↓
this bukan otomatis element
↓
ambil this dari outer scope
🧠 Inti yang Harus Kamu Ingat
Kalau dari lecture ini kamu hanya mengingat 5 kalimat, ingat ini:
1.
Di browser,
thispada global scope mengarah kewindow.
2.
Regular function yang dipanggil biasa (
fn()) menggunakanthisglobal dalam non-strict mode, tetapiundefineddalam strict mode.
3.
Pada
object.method(),thismengarah ke object yang memanggil method tersebut.
4.
Arrow function tidak memiliki
thissendiri; dia mengambilthisdari outer/parent scope.
5.
Regular function sebagai event handler bisa mendapatkan
thisberupa element DOM, sedangkan arrow function tidak otomatis mendapatkanthisdari element tersebut.
Dan menurut saya, kalimat nomor 4 adalah yang paling penting untuk menghubungkan lecture ini dengan lecture Arrow Function sebelumnya:
REGULAR FUNCTION
↓
punya this sendiri
ARROW FUNCTION
↓
tidak punya this sendiri
↓
ambil this dari parent scope
Kalau kamu sudah bisa membedakan this pada object.method(), regular function, dan arrow function, fondasi untuk memahami this di JavaScript sudah mulai kuat.