0
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?

Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82
BlackMamba
  • 10,054
  • 7
  • 44
  • 67
  • What specifically are you confused about? About [`static`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static)? What a [getter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get) is? – Felix Kling Jan 15 '16 at 05:28
  • https://stackoverflow.com/questions/30469550/es6-classes-member-properties-definitions-as-static-shared – Jaromanda X Jan 15 '16 at 05:28
  • @FelixKling i am confused about `static`. – BlackMamba Jan 15 '16 at 05:29
  • 3
    The `static` keyword declares a static method. This method becomes a property of the *constructor function*, as opposed to the prototype / instance, i.e. `Foo.bar`. See MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static . I'm surprised you ask about this [since you seem to know what `static` means](https://stackoverflow.com/questions/34804815/is-there-static-class-member-in-javascript-class-of-es6). – Felix Kling Jan 15 '16 at 05:31
  • Static methods have no access to the fields, properties, and methods defined on an instance of the class using *this*. – choz Jan 15 '16 at 05:35

2 Answers2

1

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);
Matthisk
  • 1,501
  • 10
  • 20
Akshey Bhat
  • 8,227
  • 1
  • 20
  • 20
0

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;
sundar
  • 398
  • 2
  • 12