Klasser och objekt
Testa kodexemplet:
Kodexempel
<div id="carinfo">
<!--will be filled with car data-->
</div>
<script>
class Car {
// Private fields (denoted by #)
#id;
#brand;
#model;
#year;
#price;
#isElectric;
constructor(id, brand, model, year, price, isElectric) {
this.#id = id;
this.#brand = brand;
this.#model = model;
this.#year = year;
this.#price = price;
this.#isElectric = isElectric;
}
// Public getter methods (access private fields)
get id() {
return this.#id;
}
get brand() {
return this.#brand;
}
get model() {
return this.#model;
}
get year() {
return this.#year;
}
get price() {
return this.#price;
}
get isElectric() {
return this.#isElectric;
}
// Public setter methods (modify private fields with validation)
set price(newPrice) {
if (newPrice > 0) {
this.#price = newPrice;
} else {
throw new Error("Price must be a positive number");
}
}
// Public method to display car info
//overrides this method in the Object with own code implementation
toString() {
return `${this.#brand} ${this.#model} (${this.#year}) - ${this.#price} isElectic? ${this.#isElectric}`;
}//end toString
//get car data as json object
toJSON() {
return {
id: this.#id,
brand: this.#brand,
model: this.#model,
year: this.#year,
price: this.#price,
isElectric: this.#isElectric
};
}//end toJson
}//end class
// Example usage:
//creates new Car object by calling it constructor in the array
const cars = [
new Car(1, "Toyota", "Camry", 2020, 24000, false),
new Car(2, "Tesla", "Model 3", 2022, 45000, true),
new Car(3, "Ford", "Mustang", 2021, 38000, false),
new Car(4, "BMW", "X5", 2023, 52000, true),
new Car(5, "Honda", "Civic", 2019, 22000, false),
];
const divcarinfo=document.getElementById("carinfo");
divcarinfo.innerHTML=cars[0].toString();// "Toyota Camry (2020) - 24000"
cars[0].price = 37000; // Updates price (valid)
divcarinfo.innerHTML+="<br>"+cars[0];//aslo calls toString "Toyota Camry (2020) - 37000"
cars[0].price = -100; // throws error: "Price must be positive!" look in the console
</script>