Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Prototype Syntax

Is this valid Javascript syntax? What does it do?

Parser.prototype = {

  // ...

  get currentState() {
    return this.state[this.state.length - 1];
  },

  // ...

}

See https://github.com/LearnBoost/stylus/blob/master/lib/parser.js.

Thank you!

like image 751
Betty Ellis Avatar asked Feb 13 '11 09:02

Betty Ellis


1 Answers

It defines a getter:

Binds an object property to a function that will be called when that property is looked up.

Read about Getters and Setters.

This function is called when you access the property:

var sth = obj.currentState

Notice that it is not a function call (there are no ()), but a normal property access.

A corresponding setter would look like this:

set currentState(value) {
  // do something with value
  // value would be 42 in the next example
}

and would be called when you assign a value to that property, e.g.

obj.currentState = 42;

The get and set keywords a special operators to be used inside the object literal notation. You could also use __defineGetter__ and __defineSetter__:

Parser.prototype.__defineGetter__('currentStatus', function() {
    return this.state[this.state.length - 1];
});

I'm not sure in which version it was introduced though, it might not be supported by all browsers (especially IE ;)).

like image 130
Felix Kling Avatar answered Nov 17 '22 11:11

Felix Kling