JavaScript'te this anahtar kelimesi, fonksiyonun nasıl çağrıldığına bağlı olarak farklı değerler alır. Bu da onu oldukça güçlü ama aynı zamanda karmaşık bir özellik haline getirir.
1. this Global Scope'ta Ne Anlama Gelir?
console.log(this); // window (browser'da)
- Global scope'ta
this, window objesini gösterir (browser ortamında). - Eğer
this.myVar = 1yazarsakwindow.myVarda 1 olur. this→window→ global erişim.
2. Fonksiyon İçinde this
function checkThis() {
console.log(this);
}
checkThis(); // window
- Normal fonksiyon çağrısında,
thisyinewindowolur. - Bu, katı modda (strict mode)
undefinedolur (güvenlik amacıyla).
'use strict';
function checkThis() {
console.log(this); // undefined
}
3. Nesne Metodu Olarak this
const user = {
name: "Ali",
checkThis: function() {
console.log(this);
}
};
user.checkThis(); // user objesi
- Burada
this, fonksiyonu çağıran objeyi temsil eder. - Bu, beklenen ve doğru davranıştır.
4. Fonksiyonu Değişkene Atarsak Ne Olur?
const func = user.checkThis;
func(); // window (veya undefined)
- Fonksiyonun çağrıldığı bağlam kaybolur.
- Artık
this, global objeyi gösterir. - Bağlamı korumak istiyorsak ya
bindya arrow function, ya daself = thisgibi yöntemler kullanmamız gerekit.
5. İç İçe Fonksiyonlarda this Sorunu
const obj = {
name: "Test",
outer: function () {
console.log(this); // obj
function inner() {
console.log(this); // window (veya undefined)
}
inner();
}
};
obj.outer(); // obj
outerfonksiyonu içindethisdoğru şekildeobj'yi gösterir.- Ancak içteki
innerfonksiyonu, kendi başına çağrıldığı içinthisglobal objeye döner.
✅ Çözüm: self = this
const obj = {
name: "Ali",
outer: function () {
const self = this;
function inner() {
console.log(self.name); // "Ali"
}
inner();
}
};
self,this'in referansını saklar.- Bu teknik çok yaygındır:
var self = this,const that = this,const _this = thisgibi versiyonları da vardır.
6. this Bağlamını Korumak İçin Alternatif Yöntemler
-
Arrow Function (ES6)
- Arrow fonksiyonlar kendi
thisbağlamını miras alır. Yanithisdış scope'takithisolur: -
const obj = { name: "Zeynep", outer: function () { const inner = () => { console.log(this.name); // "Zeynep" }; inner(); } };
- Arrow fonksiyonlar kendi
-
.bind()ile Sabitlemek-
function logThis() { console.log(this); } const bound = logThis.bind({ name: "Deniz" }); bound(); // { name: "Deniz" }
-
🧠 Özet: this Nasıl Belirlenir?
| Bağlam | this neyi gösterir? |
|---|---|
Global scope ( this ) |
window (ya da global ) |
Fonksiyon ( check() ) |
window (strict mode'da undefined ) |
Nesne metodu ( obj.method() ) |
obj |
| Arrow function | Dış scope’taki this |
.bind(this) |
Manuel olarak bağlanan değer |