Asosiy matnga o'tish
ITIT Interview
JavaScript

this

this qiymati qanday aniqlanadi, call, apply, bind, arrow funksiyalarda this va kontekst yo'qolishi.

O'rganildi: 0 / 5
Progress

Bu nima?

this funksiya qanday chaqirilganiga qarab aniqlanadigan kalit so'z. U funksiya qayerda yozilganiga emas (arrow funksiyalar bundan mustasno), chaqiruv paytidagi kontekstga bog'liq.

this ni aniqlash qoidalari

Tartib bilan, birinchi mos kelgani g'olib:

ChaqiruvthisMisol
new bilanYangi yaratilgan obyektnew User()
call / apply / bindAniq berilgan obyektfn.call(obj)
Obyekt metodi sifatidaNuqtadan oldingi obyektuser.greet()
Oddiy chaqiruvundefined (strict mode), window (oddiy rejim)greet()
Arrow funksiyaTashqi (leksik) scope'ning this i() => this
const user = {
  name: 'Ali',
  greet() {
    return `Salom, ${this.name}`;
  },
};

user.greet();            // "Salom, Ali" — this = user

const fn = user.greet;
fn();                    // this = undefined -> xato yoki "Salom, undefined"

Kontekst yo'qolishi

Metod boshqa joyga berilganda (callback, event handler) this yo'qoladi:

class Timer {
  seconds = 0;
  start() {
    setInterval(function () {
      this.seconds++;    // this = undefined/window, Timer emas!
    }, 1000);
  }
}

Yechimlar:

// 1. Arrow funksiya: this tashqaridan olinadi
setInterval(() => { this.seconds++; }, 1000);

// 2. bind
setInterval(function () { this.seconds++; }.bind(this), 1000);

// 3. Klass maydoni sifatida arrow
class Button {
  label = 'OK';
  handleClick = () => console.log(this.label);
}

call, apply, bind

function introduce(city, job) {
  return `${this.name}, ${city}, ${job}`;
}
const person = { name: 'Vali' };

introduce.call(person, 'Toshkent', 'dasturchi');     // argumentlar ketma-ket
introduce.apply(person, ['Toshkent', 'dasturchi']);  // argumentlar massivda
const bound = introduce.bind(person, 'Toshkent');    // yangi funksiya qaytaradi
bound('dizayner');
Darhol chaqiradimiArgumentlar
callHaKetma-ket
applyHaMassiv
bindYo'q, yangi funksiya qaytaradiKetma-ket (qisman qo'llash mumkin)

Arrow funksiyalar va this

const obj = {
  name: 'Ali',
  regular() { return this.name; },     // "Ali"
  arrow: () => this.name,              // undefined: this obyekt emas, tashqi scope
};

Shuning uchun obyekt metodlarini arrow bilan yozmaslik kerak, callback'lar ichida esa arrow juda qulay.

Intervyu savollari

Ushbu sahifada