finals in JavaScript

Java has final fields, parameters and local variables. And JavaScript 2.0 has const modifier. But, there is no support for finals or consts in JavaScript 1.x (although const and final are reserved words). We will see how we can implement equivalent of finals in JavaScript (in Mustang's JavaScript engine).


function finals() {
    var map = new Object();
    return new JSAdapter() {
        __put__ : sync(function (name, value) {
            // already exists, do not allow assignment again
            if (name in map) {
                throw "can't modify final field";   
            }
            // does not exist in map, allow first assignment
            map[name] = value;
        }),
        __get__ : sync(function (name) {
            return map[name];
        }),
        __has__ : sync(function (name) {
            return name in map;
        })
     }
}


Note that the sync built-in is used to wrap the methods so that the object returned by finals function is MT-safe. Let us assume that the above code is stored in a file named "finals.js". Now, we can start jrunscript using the following command line:

jrunscript -f finals.js -f -

The interactive jrunscript session is shown below:

js> var constants = finals()
com.sun.script.javascript.JSAdapter@a8c488
js> constants.x = 3
3.0
js> constants.x = 34

script error: sun.org.mozilla.javascript.internal.EvaluatorException: can't modify
final field (finals.js#7) (<STDIN>#1) in <STDIN> at line number 1

js> constants.y = 4
4.0
js> constants.y
4.0
js> constants.x
3.0
js> constants.y = 5656

script error: sun.org.mozilla.javascript.internal.EvaluatorException: can't modify
final field (finals.js#7) (<STDIN>#1) in <STDIN> at line number 1

js> quit()

A finals objects like 'constants' may be used with JavaScript with statement so that the properties may be accessed like variables (without the obj.field syntax).

Comments:

AIFAK in Js 1.5 the modifier const exists: http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Statements:const

Posted by Mark on December 28, 2005 at 05:59 AM IST #

It seems that 'const' modifier is implemented only in JavaScript engine implemented in "C". The reference link you have quoted says: "JavaScript 1.5, NES 6.0 (Netscape extension, C engine only)" Mustang uses Rhino (JavaScript Java engine).

Posted by A. Sundararajan on January 02, 2006 at 06:41 AM IST #

Post a Comment:
Comments are closed for this entry.
About

sundararajan

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today
Bookmarks
Links

No bookmarks in folder

Blogroll

No bookmarks in folder

News

No bookmarks in folder