The get
syntax binds an object property to a function that will be called when that property is looked up.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get
The more general and exhausting explanation can be found here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters
Basically, it allows you to define what happens when a certain object property is read by code. In an analogous fashion, you can also define what should happen when code writes to that property with a set
definition. In both cases you overwrite the standard behaviour for that object property.
This is all part of ECMAScript 5.1, and thus, not available in IE < 9.
What does your example code do?
In your example code, you can see that whenever the property DEFAULT_WIDTH is read, a constant value will be returned. I guess the intention of this is to make sure DEFAULT_WIDTH cannot be redefined as some other value (which it in fact can, but reading it will still return 50).
Defining a getter on existing objects using defineProperty
To append a getter to an existing object later at any time, use Object.defineProperty()
.
var o = { a:0 }
Object.defineProperty(o, "b", { get: function () { return this.a + 1; } });
console.log(o.b) // Runs the getter, which yields a + 1 (which is 1)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get#Defining_a_getter_on_existing_objects_using_defineProperty