Sobes.tech
Middle

JavaScriptda `this` ning bajarilish kontekstining qiymati nima bilan bog'liq?

sobes.tech AI

AIdan javob

JavaScript'da this qiymati funksiyani qanday chaqirilishiga bog‘liq. Asosiy holatlar:

  1. Global kontekst: Funktsiyalar tashqarida, qatʼiy rejimda ('use strict') this undefined bo‘ladi. Qatʼiy rejimda emas, this global obyekti (window brauzerda, global Node.jsda).

  2. Obyekt metodini chaqirish: this chaqirilayotgan metodga tegishli obyekti ko‘rsatadi.

    const obj = {
      prop: 'qiymat',
      method: function() {
        // this === obj
        console.log(this.prop);
      }
    };
    obj.method();
    
  3. Oddiy funksiyani chaqirish: Qatʼiy rejimda this undefined. Qatʼiy rejimda emas, this global obyekti.

    function myFunction() {
      // qatʼiy rejimda this === undefined
      // qatʼiy rejimda emas, this === window (brauzerda)
      console.log(this);
    }
    myFunction();
    
  4. Konstruktor (new): new operatori bilan konstruktor funksiyasidan foydalanilganda, this yangi yaratilgan obyekti ko‘rsatadi.

    function MyClass(name) {
      this.name = name; // this === yangi obyekti
    }
    const instance = new MyClass('test');
    // instance.name === 'test'
    
  5. Aniq bog‘lash (call, apply, bind): call, apply va bind metodlari this qiymatini aniq belgilashga imkon beradi.

    • call(thisArg, arg1, arg2, ...): Funksiyani chaqiradi, this ni thisArg ga o‘rnatadi va argumentlarni alohida uzatadi.
    • apply(thisArg, [argsArray]): Funksiyani chaqiradi, this ni thisArg ga o‘rnatadi va argumentlarni massiv sifatida uzatadi.
    • bind(thisArg): Doimiy ravishda this bilan bog‘langan yangi funksiyani qaytaradi.
    const anotherObj = { value: 42 };
    function showValue() {
      console.log(this.value);
    }
    showValue.call(anotherObj); // 42 ni chiqaradi
    
  6. Qisqa funksiyalar (=>): Qisqa funksiyalar o‘z thisiga ega emas. this qiymati, u aniqlangan leksikal kontekstdan meros oladi.

    const outerObj = {
      name: 'Outer',
      method: function() {
        const arrowFunc = () => {
          // this outerObj ning method sifatida chaqirilganidan meros oladi
          console.log(this.name);
        };
        arrowFunc();
      }
    };
    outerObj.method(); // 'Outer' ni chiqaradi
    
    const anotherArrowFunc = () => {
        // this global kontekstdan meros oladi (yoki qatʼiy rejimda undefined)
        console.log(this);
    };
    anotherArrowFunc();
    
  7. DOM hodisa ishlovchilari: Ko‘pgina hollarda, hodisa ishlovchida this hodisa yuz beradigan DOM elementiga ishora qiladi.

    // Brauzerda misol
    const button = document.querySelector('button');
    button.addEventListener('click', function() {
      // this === button
      console.log(this.tagName);
    });
    

Bu mexanizmlarni tushunish JavaScriptda thisni to‘g‘ri ishlatish uchun juda muhim.