You can use Object.freeze(o); to make an object immutable in newish browsers.
The Point2D could thus be implemented like this:
var Point2D = function(x, y) {
this.x = x;
this.y = y;
Object.freeze(this);
}
Now no new properties can be added to a Point2D object and it's existing properties can not be altered:
> var p = new Point2D(99, 123)
undefined
> p.x
99
> p.x = 7
7
> p.x
99
> p.foo = "This won't be added"
undefined
> JSON.stringify(p);
"{"x":99,"y":123}"
If you only want to lock down the object to not have any new properties added then you can use Object.seal(o); instead. This will allow you to mutate existing properties, but not add new ones.
> var o = {x:1, y:2}
undefined
> Object.seal(o);
[object Object]
> JSON.stringify(o);
"{"x":1,"y":2}"
> o.foo = "This won't be added";
99
> o.x = 37 // Seal allows to mutate object
37
JSON.stringify(o);
"{"x":37,"y":2}"
freeze and seal is part of ECMAScript 5.1 described more formally here
MDN states that freeze is supported in:
- Firefox (Gecko) 4 (2.0)
- Chrome 6
- Internet Explorer 9
- Opera 12
- Safari 5.1
Alternatively, you could use a more functional coding style:
var Point2D = function(x, y) {
return function(prop) {
switch (prop) {
case "x": return x;
case "y": return y;
default: throw new Error("Property '" + prop + "' not supported");
}
};
}
Usage would then be like:
> var p = Point2D(1,2)
undefined
> p("x")
1
> p("y")
2
> p("foo")
Error: Property 'foo' not supported
I know of no way to alter the "properties" x and y using this aproach since they are bound by the scope of the Point2D function. This approach is not commonly seen in javascript (as far as I know), but is similar to how message passing/OO can be achieved in for instance Scheme.