« F3 - Open Definition | Main | Definite assignment »
Tuesday
Dec142010

Object Literals

Release 1.7.3 adds full support for object literals.

Sometimes you just need a single, unique object. The easiest way to achieve this is an object literal. Example:

    var x = { 
              _v:1, 
              get_v : function(){ return this._v; }
            };
    var y = x.get_v();

This common pattern is now fully supported including type verification and code completion.

Furthermore you can now use getters and setters in object literals, which is some of the new syntax syntax in ECMAScript 5:

    var x = { 
             _v:0, 
             set v(x){ this._v = x; }, 
             get v(){ return this._v; }
             };
    x.v = 100;
    var y = x.v;

(Note that the getter/setter syntax is slightly different in object literals - you don’t need the function keyword here.)

Object literals are most convenient when you only need a single instance of an object. For example a global object literal is the equivalent to the singleton pattern as in Java - but the syntax is much simpler.

The limitations are that an object literal does not support inheritance. If you need that, a class is better.

PrintView Printer Friendly Version

EmailEmail Article to Friend