Sobes.tech
Middle

JavaScript'te fonksiyonların bağlamı hakkında konuş.

sobes.tech yapay zeka

AI'dan gelen yanıt

JavaScript'te bir fonksiyonun (this) yürütme bağlamı, fonksiyonun nasıl çağrıldığını ve içinde hangi değerlerin erişilebilir olduğunu belirler. Bağlam, çağrı şekline bağlı olarak dinamik olarak değişir:

  • Küresel bağlam: Fonksiyonların dışında, this küresel nesneye atıfta bulunur (window tarayıcıda, global Node.js'te).
    // Tarayıcıda
    console.log(this === window); // true
    
    // Node.js'te
    console.log(this === global); // true
    
  • Fonksiyon bağlamı:
    • Standart çağrı: Non-strict modda, fonksiyon içindeki this küresel nesneye atıfta bulunur (eğer fonksiyon bir nesne yöntemi değilse). Strict modda ("use strict";) this undefined olur.
      function showThis() {
        console.log(this);
      }
      
      showThis(); // Non-strict modda: Global nesne; Strict modda: undefined
      
    • Bir nesnenin yöntemi olarak çağrı: this, yöntemin ait olduğu nesneye atıfta bulunur.
      const user = {
        name: 'Alice',
        greet: function() {
          console.log("Merhaba, benim adım " + this.name);
        }
      };
      
      user.greet(); // Merhaba, benim adım Alice
      
    • new ile çağrı (yapıcı fonksiyon): Yeni bir nesne oluşturur, bu nesne fonksiyonun içindeki this değeri olur ve bu nesne döndürülür.
      function Person(name) {
        this.name = name;
      }
      
      const person1 = new Person('Bob');
      console.log(person1.name); // Bob
      
    • Açıkça bağlam belirtme (call, apply, bind):
      • call(thisArg, arg1, arg2, ...): Fonksiyonu, belirtilen this ve argümanlarla çağırır.
      • apply(thisArg, [argsArray]): Fonksiyonu, belirtilen this ve argümanlar dizisiyle çağırır.
      • bind(thisArg, arg1, arg2, ...): Yeni bir fonksiyon döndürür, bu fonksiyonun this değeri kalıcı olarak thisArg'a bağlanır ve argümanlar önceden bağlanır.
      function introduce(greeting, punctuation) {
        console.log(greeting + ", ben " + this.name + punctuation);
      }
      
      const person = { name: 'Charlie' };
      
      introduce.call(person, "Merhaba", "!");  // Merhaba, ben Charlie!
      introduce.apply(person, ["Selam", "."]); // Selam, ben Charlie.
      
      const boundIntroduce = introduce.bind(person, "Hey");
      boundIntroduce("?"); // Hey, ben Charlie?
      
  • Ok fonksiyonlar: Kendi this bağlamlarına sahip değildir. Tanımlandıkları kapsayıcı bağlamdan this'i yakalarlar.
    const obj = {
      name: 'David',
      sayLater: function() {
        // `this` burada `obj`'e referans eder
        setTimeout(() => {
          // `this` burada da `obj`'e referans eder (sayLater'dan kalıtılmış)
          console.log("Sonra, ben " + this.name);
        }, 1000);
      }
    };
    
    obj.sayLater(); // Sonra, ben David