class Foo {
static get bar() {
return 42;
}
get bar() {
return 21;
}
}
I am confused about static get bar() { return 42; }
,
what's the purpose of this code? who can give me a clear explantion?
class Foo {
static get bar() {
return 42;
}
get bar() {
return 21;
}
}
I am confused about static get bar() { return 42; }
,
what's the purpose of this code? who can give me a clear explantion?
static get bar()
is a getter which is not instance specific. It can be used without creating an instance of class Foo
as given below:
alert(Foo.bar);
whereas
get bar()
is an object specific getter. It can only be used after creating object of class as given below:
var obj = new Foo();
alert(obj.bar);
static is similar to the static keyword in other programming languages(like java, .net ...etc)
when ever you have static property(method, variable) in your class that has been created only once, and shared across all your class objects instances.
For example if you want to have total users count inside of your class you can do that by using static keyword
Example:
class User {
Constructor() {
}
set name(name) {
this.name = name;
}
get name() {
return this.name;
}
static userCount;
}
when ever you create new user instances you can increment your users count.any of your users can access the userCount variable.To access static variable you cannot use this keyword.because it does not belongs to any instances.so to access static keyword use the following
User.userCount = 0;