Skip to content

Cum sa intelegi cuvantul cheie this in JavaScript

DodaTech Updated 2025-01-15 3 min read

In this tutorial, you'll learn about Cum sa intelegi cuvantul cheie this in JavaScript. We cover key concepts, practical examples, and best practices.

Cuvantul cheie this in JavaScript este adesea confuzant deoarece valoarea sa depinde de modul in care este apelata functia. Acest ghid iti explica toate cazurile si cum sa controlezi contextul.

Quick Fix

1. this in context global

In browser, this global este window; in Node.js este global:

console.log(this === window); // In browser: true

2. this intr-o metoda a unui obiect

Cand o functie este apelata ca metoda, this este obiectul:

const user = {
    name: 'Ion',
    greet() {
        return `Salut, sunt ${this.name}`;
    }
};

console.log(user.greet());
Salut, sunt Ion

3. this intr-o functie normala

In functii simple (non-strict mode), this este global; in strict mode, undefined:

function showThis() {
    'use strict';
    console.log(this);
}

showThis(); // undefined (strict mode)

4. this in arrow functions

Arrow functions nu au propriul this -- il mostenesc din contextul lexical:

const user = {
    name: 'Ana',
    hobbies: ['citit', 'programare'],
    showHobbies() {
        this.hobbies.forEach(hobby => {
            // this este mostenit din showHobbies
            console.log(`${this.name} prefera ${hobby}`);
        });
    }
};

user.showHobbies();
Ana prefera citit
Ana prefera programare

5. Controlul contextului cu bind

bind() creeaza o functie noua cu this fixat:

const user = { name: 'Ion' };

function greet(greeting) {
    return `${greeting}, ${this.name}!`;
}

const greetIon = greet.bind(user);
console.log(greetIon('Salut'));
Salut, Ion!

6. call si apply pentru apeluri cu context

call() si apply() apeleaza functia cu un this specificat:

const user1 = { name: 'Ana' };
const user2 = { name: 'Ion' };

function introduce(age, city) {
    return `${this.name}, ${age} ani, ${city}`;
}

// call: argumente individuale
console.log(introduce.call(user1, 25, 'Cluj'));

// apply: argumente in array
console.log(introduce.apply(user2, [30, 'Bucuresti']));
Ana, 25 ani, Cluj
Ion, 30 ani, Bucuresti

7. this in clase

In clase, this se refera la instanta:

class Button {
    constructor(text) {
        this.text = text;
        this.count = 0;
    }

    handleClick() {
        this.count++;
        console.log(`Butonul "${this.text}" apasat de ${this.count} ori`);
    }
}

const btn = new Button('Salveaza');
btn.handleClick();
btn.handleClick();
Butonul "Salveaza" apasat de 1 ori
Butonul "Salveaza" apasat de 2 ori

Prevention

  • Foloseste arrow functions pentru callback-uri (setTimeout, evenimente) pentru a pastra this
  • Foloseste bind() cand passezi o metoda ca referinta
  • Nu extrage metode din obiecte fara sa pastrezi contextul
  • In React, bind() metodele in constructor sau foloseste class fields cu arrow functions

Common Mistakes

  1. A pierde contextul in callback-uri -- setTimeout(obj.method, 1000) pierde this; foloseste obj.method.bind(obj) sau arrow function
  2. A folosi arrow functions ca metode -- { name: 'Ion', greet: () => console.log(this.name) } -- this nu este obiectul
  3. A extrage o metoda fara context -- const fn = obj.method; fn() pierde this (fara strict mode, devine global)
  4. A uita de strict mode -- fara 'use strict', this in functii normale este obiectul global
  5. A crede ca this in arrow functions poate fi rebinded -- bind()/call()/apply() nu functioneaza pe arrow functions

FAQ

### Cum determin valoarea lui this intr-o functie?

Regula: "Cine a apelat functia?" Daca este apelata ca metoda a unui obiect (obj.fn()), this este obj. Daca este apelata liber (fn()), this este global sau undefined (strict mode).

De ce this se pierde in setTimeout?

Pentru ca setTimeout(obj.method, 1000) extrage metoda si o apeleaza ca functie libera, nu ca metoda. Solutie: setTimeout(() => obj.method(), 1000) sau setTimeout(obj.method.bind(obj), 1000).

Pot schimba this intr-o arrow function?

Nu. Arrow functions nu au propriul this. bind(), call() si apply() pe arrow functions sunt ignorate -- this ramane cel din contextul lexical.

Construit de dezvoltatorii Doda Browser, DodaZIP si Durga Antivirus Pro. Instrumentele DodaTech se integreaza perfect cu JavaScript pentru productivitate si securitate sporite.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro