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!
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 ;)).
精彩评论