5

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!

asked Feb 13, 2011 at 9:50

1 Answer 1

5

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 ;)).

answered Feb 13, 2011 at 10:21
Sign up to request clarification or add additional context in comments.

1 Comment

It was introduced in ECMAScript 5, and IE9 was the first browser with a functional ES5 engine.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.