You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
A static method or property belongs to the class itself, not to any object created from it.
63
+
INFO: What is static keyword in classes ?
64
+
The static keyword in javascript classes is used to define properties or methods that belongs to the class itself, not to instances of the clases. Static members are accessed directly via the class name, not through an instance.
64
65
*/
65
66
66
67
// Example
67
68
classCar{
69
+
staticcount=0;
70
+
68
71
constructor(model){
69
72
this.model=model;
73
+
Car.count++
70
74
}
71
75
72
76
staticcompany(){
73
77
return"Toyota";
74
78
}
79
+
80
+
staticgetCount(){
81
+
returnCar.count;
82
+
}
75
83
}
76
84
85
+
console.log(Car.count);// 1
77
86
constmyCar=newCar("BMW");
78
87
79
88
console.log(Car.company());// Toyota
89
+
console.log(Car.getCount());// 2
80
90
console.log(myCar.company());// Error: myCar.company is not a function
81
91
82
92
83
-
// INFO: get and set (Getters & Setters)
93
+
/* INFO: get and set (Getters & Setters)
94
+
Getters and setters in javascript are special methods that allow you to define custom behaviour when accessing or setting object properties.
95
+
*/
84
96
85
97
/*
86
98
INFO: What is getter ?
87
-
A getter allows you to access a property like a variable, but it actually runs a fucntion behind the scenes.
99
+
get lets you retrieve (read) a property like a variable, but it's actually a function.
88
100
*/
89
101
90
102
/*
91
103
INFO: What is setter ?
92
-
A setter allows you to control how a property is set (add validation, logs, etc.)
104
+
set lets you update (write) a property like a variable, but with custom logic behind it.
93
105
*/
94
106
95
-
classEmployee{
107
+
// Syntax
108
+
classMyClass{
96
109
constructor(name){
97
-
this.name=name;
110
+
this._name=name;
98
111
}
99
112
100
113
getname(){
101
-
returnthis._name.toUpperCase();
114
+
returnthis._name;
115
+
}
116
+
117
+
setname(newName){
118
+
this._name=newName;
119
+
}
120
+
}
121
+
122
+
// Convention: Use an underscore _name to store the actual value so it doesn't clash with the getter/setter.
0 commit comments