Previous: , Up: Static Members   [Contents]


2.3.3 Constants

Constants, in terms of classes, are immutable static properties. This means that, once defined, a constant cannot be modified. Since the value is immutable, it does not make sense to create instances of the property. As such, constant values are implicitly static. This ensures that each instance, as well as any static access, references the exact same value. This is especially important for objects and arrays.

One important difference between other languages, such as PHP, is that ease.js supports the visibility modifiers in conjunction with the const keyword. That is, you can have public, protected and private constants. Constants are public by default, like every other type of member. This feature permits encapsulating constant values, which is important if you want an immutable value that shouldn’t be exposed to the rest of the world (e.g. a service URL, file path, etc). Consider the following example in which we have a class responsible for reading mount mounts from /etc/fstab:

    Class( 'MountPointIterator',
    {
        'private const _PATH': '/etc/fstab',

        'private _mountPoints': [],


        __construct: function()
        {
            var data = fs.readFileSync( this.$('_PATH') );
            this._parseMountPoints( data );
        },

        // ...
    } );

Figure 2.27: Using the const keyword

In the above example, attempting to access the _PATH constant from outside the class would return undefined. Had the constant been declared as public, or had the visibility modifier omitted, it could have been accessed just like any other static property:

    // if PATH were a public constant value
    MountPointIterator.$('PATH');

Any attempts to modify the value of a constant will result in an exception. This will also work in pre-ES5 engines due to use of the static accessor method ($()).

It is important to note that constants prevent the value of the property from being reassigned. It does not prevent modification of the value that is referenced by the property. For example, if we had a constant foo, which references an object, such that

    'const foo': { a: 'b' }

it is perfectly legal to alter the object:

    MyClass.$('foo').a = 'c';

Previous: , Up: Static Members   [Contents]