Skip to content

Commit 6f5e45c

Browse files
committed
geter seter indepth
1 parent fab66ca commit 6f5e45c

File tree

1 file changed

+51
-12
lines changed

1 file changed

+51
-12
lines changed

11_OOP/geterseter.js

Lines changed: 51 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,58 @@
1-
class car{
2-
constructor(brand, model, year){
3-
this.brand = brand;
4-
this.model = model;
5-
this.year = year;
1+
// class car{
2+
// constructor(brand, model, year){
3+
// this._brand = brand;
4+
// this._model = model;
5+
// this._year = year;
6+
// }
7+
// get readme(){
8+
// return this._brand + ' ' + this._model + ' ' + this._year;
9+
// }
10+
// set setme(value){
11+
// this._brand = value;
12+
// }
13+
// }
14+
15+
16+
17+
// let mycar = new car('ford', 'mustang', 2023);
18+
19+
// mycar.readme = 'BMW' //setter
20+
21+
// console.log(mycar.readme) //getter
22+
23+
class Car {
24+
constructor(brand, model, year) {
25+
this._brand = brand; // real storage
26+
this._model = model;
27+
this._year = year;
628
}
7-
get carname(){
8-
return this.brand + ' ' + this.model + ' ' + this.year;
29+
30+
// Getter for model (to read it)
31+
get model() {
32+
return this._model;
33+
}
34+
35+
// Setter for model (to change it)
36+
set model(value) {
37+
this._model = value;
938
}
10-
set carname(value){
11-
this.brand = value;
39+
40+
// Extra: Get full info about the car
41+
get info() {
42+
return `${this._brand} ${this._model} ${this._year}`;
1243
}
1344
}
1445

15-
let mycar = new car('ford', 'mustang', 2023);
46+
// Create a car object
47+
let myCar = new Car('Ford', 'Mustang', 2023);
48+
49+
// Read the model using getter
50+
// console.log(myCar.model); // 👉 Mustang
51+
52+
// Change the model using setter
53+
myCar.model = 'Explorer';
1654

17-
mycar.carname = 'BMW' //setter
55+
// Read the full car info
56+
// console.log(myCar.info); // 👉 Ford Explorer 2023
1857

19-
console.log(mycar.carname) //getter
58+
console.log(myCar)

0 commit comments

Comments
 (0)