- A variable is given public scope if it is supposed to be accessed outside the class.
- Eg:- In a
Stack
class, 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
Stack
class, we would want the variabletop
to be private since the only operations that should be publically available to aStack
object 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
Stack
class, we would want the variabletop
to 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
Date
class, we could have a static method callednow
which gives us the current time, which in context of aDate
object would not make sense...since what wouldnow()
on a date object mean?...Eg: callingnow()
a date "29/03/1998" seems foolish. ADate
object could be assigned the value ofDate.now()
but callingnow()
on aDate
object wouldnt make sense as mentioned earlier and hence it is undefined for an object/instance of theDate
class.
class Date{
static now(){
}
}