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).
Posted by Mark on December 28, 2005 at 01:59 PM IST #
Posted by A. Sundararajan on January 02, 2006 at 02:41 PM IST #