←

"this" Nedir ve Nasıl Çalışır?

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)

 

2. Fonksiyon İçinde  this 

function checkThis() {
	console.log(this);
}
checkThis(); // window
'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

 

4. Fonksiyonu Değişkene Atarsak Ne Olur?

const func = user.checkThis;
func(); // window (veya undefined)

 

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

✅ Çözüm:  self = this 

const obj = {
	name: "Ali",
	outer: function () {
		const self = this;
		function inner() {
			console.log(self.name); // "Ali"
		}
		inner();
	}
};

 

6.  this  Bağlamını Korumak İçin Alternatif Yöntemler

 

🧠 Ö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