Cum sa folosesti clase in JavaScript
In this tutorial, you'll learn about Cum sa folosesti clase in JavaScript. We cover key concepts, practical examples, and best practices.
Clasele in JavaScript ofera o sintaxa clara pentru a crea obiecte si a gestiona mostenirea prin prototipuri. Acest ghid iti arata cum sa folosesti clase moderne.
Quick Fix
1. Definirea unei clase de baza
Foloseste cuvantul cheie class si constructor:
class User {
constructor(name, email) {
this.name = name;
this.email = email;
this.createdAt = new Date();
}
getInfo() {
return `${this.name} <${this.email}>`;
}
isNew() {
const daysSinceCreation = (Date.now() - this.createdAt) / 86400000;
return daysSinceCreation < 7;
}
}
const user = new User('Ion Popescu', 'ion@example.com');
console.log(user.getInfo());
Ion Popescu <ion@example.com>
2. Getteri si setteri
Foloseste get si set pentru proprietati calculate:
class Product {
constructor(price, vatRate = 0.19) {
this._price = price;
this._vatRate = vatRate;
}
get priceWithVAT() {
return this._price * (1 + this._vatRate);
}
set price(value) {
if (value < 0) throw new Error('Pretul nu poate fi negativ');
this._price = value;
}
get price() {
return this._price;
}
}
const p = new Product(100);
console.log(p.priceWithVAT);
p.price = 200;
console.log(p.priceWithVAT);
119
238
3. Mostenire cu extends si super
extends creeaza o clasa parinte, super apeleaza constructorul parinte:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} face un sunet.`;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
speak() {
return `${this.name} latra!`;
}
getBreed() {
return this.breed;
}
}
const dog = new Dog('Rex', 'Ciobanesc');
console.log(dog.speak());
console.log(dog.getBreed());
Rex latra!
Ciobanesc
4. Metode statice
Metodele statice se apeleaza pe clasa, nu pe instanta:
class MathUtils {
static add(a, b) {
return a + b;
}
static fromJSON(json) {
const data = JSON.parse(json);
return new User(data.name, data.email);
}
}
console.log(MathUtils.add(5, 3));
8
5. Proprietati private (campuri #)
Foloseste # pentru campuri si metode private:
class BankAccount {
#balance = 0;
constructor(owner) {
this.owner = owner;
}
deposit(amount) {
if (amount <= 0) throw new Error('Suma invalida');
this.#balance += amount;
return this.#balance;
}
getBalance() {
return this.#balance;
}
}
const account = new BankAccount('Ion');
account.deposit(500);
console.log(account.getBalance());
500
Prevention
- Apeleaza
super()in constructorul clasei derivate inainte de a accesathis - Foloseste campuri
#private pentru incapsulare reala - Nu confunda mostenirea cu compozitia -- nu mosteni doar pentru a reutiliza cod
Common Mistakes
- A uita
super()in constructorul derivat -- cauzeaza ReferenceError: Must call super constructor - A confunda metode statice cu metode de instanta -- metodele statice nu au acces la
thisal instantei - A incerca sa accesezi campuri
#din afara clasei -- proprietatile private sunt inaccesibile in afara - A nu folosi
newpentru a instantia -- faranew,thiseste undefined in strict mode - A suprascrie metode fara
super-- daca vrei sa extinzi comportamentul, nu sa-l inlocuiesti, folosestesuper.metoda()
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