- A variable is given public scope if it is supposed to be accessed outside the class.
- Eg:- In a
Stackclass, we would want the methodpush()to be public.
class Stack{
push(){
}
}- A variable is given private scope if dont want it to be accessed directly/modified by any entity outside its own class.
- In an explicit JS class such variables are prefixed with
#to signify that they are private members of the class. - Eg:- In a
Stackclass, we would want the variabletopto be private since the only operations that should be publically available to aStackobject are pushing, popping, getting the size, and accessing the value of the top but not modifying it(which are done using privileged methods (discussed below)) of the stack.
class Stack{
#top;
push(){
}
}- Privileged methods can be used to access private variables by exposing themselves as public methods
- Eg:- In a
Stackclass, we would want the variabletopto be private, but to access its value without allowing modification we would need its value to be exposed by a public method which gets the property of privileged because of its behaviour.
class Stack{
#top;
push(){
}
get_top(){
return this.#top;
}
}- Static methods are used to provide exclusive functionality to a Class itself rather than to objects/instances of it
- Eg:- In a
Dateclass, we could have a static method callednowwhich gives us the current time, which in context of aDateobject would not make sense...since what wouldnow()on a date object mean?...Eg: callingnow()a date "29/03/1998" seems foolish. ADateobject could be assigned the value ofDate.now()but callingnow()on aDateobject wouldnt make sense as mentioned earlier and hence it is undefined for an object/instance of theDateclass.
class Date{
static now(){
}
}