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?

5
  • What specifically are you confused about? About static? What a getter is? Commented Jan 15, 2016 at 5:28
  • stackoverflow.com/questions/30469550/… Commented Jan 15, 2016 at 5:28
  • @FelixKling i am confused about static. Commented Jan 15, 2016 at 5: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: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… . I'm surprised you ask about this since you seem to know what static means. Commented Jan 15, 2016 at 5:31
  • Static methods have no access to the fields, properties, and methods defined on an instance of the class using this. Commented Jan 15, 2016 at 5:35

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

If get bar() is a getter, could use it like this alert(obj.bar);, not alert(obj.bar());?
yes you are right @BlackMamba. Sorry my bad. Modified my answer.
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;

2 Comments

Could i write static userCount = 0;?
yes you can do like that.I hope that makes you unserstand static pretty good

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.