Sobes.tech
Junior

JavaScript-də kontekst nədir?

sobes.tech Süni İntellekt

AI-dan cavab

JavaScript-də (this) kontekst, cari funksiyanın icra olunduğu obyektə istinad edir. Onun dəyəri funksiyanın necə çağrıldığına görə müəyyən edilir, onun təyin olunduğu yerə deyil.

Konteksti müəyyən etməyin əsas üsulları:

  • Qlobal kontekst: Funksiyaların xaricində, qeyri-sert rejimdə, this qlobal obyektə (window brauzerdə, global Node.js-də) istinad edir. Sert rejimdə, this undefined olur.

    // Qeyri-sert rejim (brauzer)
    console.log(this === window); // true
    
    // Sert rejim
    "use strict";
    console.log(this === undefined); // true
    
  • Obyektin metodu: Əgər funksiya obyektin metodu kimi çağrılırsa (obj.method()), this funksiyanın içində həmin obyektə (obj) istinad edir.

    const user = {
        name: "John",
        greet: function() {
            console.log("Hello, " + this.name);
        }
    };
    user.greet(); // Çıxış: Hello, John (this, user-ə istinad edir)
    
  • Funktsiyanın çağırılması (call, apply, bind): callapply metodları funksiyanı açıq şəkildə göstərilən kontekstlə çağırır. bind isə, sabit kontekstlə yeni funksiya yaradır.

    function sayName(greeting) {
        console.log(greeting + ", " + this.name);
    }
    
    const person = { name: "Peter" };
    
    sayName.call(person, "Hi"); // Çıxış: Hi, Peter (this = person)
    sayName.apply(person, ["Hello"]); // Çıxış: Hello, Peter (this = person)
    
    const boundSayName = sayName.bind(person, "Hey");
    boundSayName(); // Çıxış: Hey, Peter (this = person)
    
  • Konstruktor (new): new operatoru ilə funksiyanı çağıranda, yeni boş obyekt yaradılır və this konstruktor funksiyada həmin yeni obyektə istinad edir.

    function Person(name) {
        this.name = name;
    }
    
    const john = new Person("John");
    console.log(john.name); // Çıxış: John (this, Person daxilində, john-a istinad edir)
    
  • Ox funksiyalar: Ox funksiyaları öz kontekstinə malik deyil. this içindəki ox funksiyada, funksiyanın yaradıldığı xarici (lexikal) mühitdən götürülür.

    const user = {
        name: "Alice",
        greet: function() {
            const innerGreet = () => {
                console.log("Hello, " + this.name); // this, greet-dən götürülür (user-ə istinad edir)
            };
            innerGreet();
        }
    };
    user.greet(); // Çıxış: Hello, Alice
    

this-in necə müəyyən olunduğunu başa düşmək, JavaScript-də obyektlər, metodlar və hadisə idarəçiləri ilə düzgün işləmək üçün çox vacibdir.