Search code examples
javascriptgetterobject-literal

What does it do when a method definition inside an object literal is prefixed by the `get` keyword?


I'm using the library handsontable and I'd like to get my application running in IE8-IE9 (even though it's not IE < 10 compatible...). When my code use the minify version I get an error in the JS console : "';' expected".

Here is the code.

{
    get DEFAULT_WIDTH() {
        return 50;
    }
}

I just don't know this syntax. What does get DEFAULT_WIDTH() do?


Solution

  • 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