Cum sa intelegi cuvantul cheie this in JavaScript
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
- A pierde contextul in callback-uri --
setTimeout(obj.method, 1000)pierdethis; folosesteobj.method.bind(obj)sau arrow function - A folosi arrow functions ca metode --
{ name: 'Ion', greet: () => console.log(this.name) }--thisnu este obiectul - A extrage o metoda fara context --
const fn = obj.method; fn()pierdethis(fara strict mode, devine global) - A uita de strict mode -- fara
'use strict',thisin functii normale este obiectul global - A crede ca
thisin arrow functions poate fi rebinded --bind()/call()/apply()nu functioneaza pe arrow functions
FAQ
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