It seems to me that immutable types are impossible in Javascript, or does anyone know of any tricks to create them? Is it a good or bad practice?
For instance something like,
var Point2D = function Point2D(x, y) {
var _x = x;
var _y = y;
function constructor() {
var self = {};
// Pseudo-Immutable concept
self.x = function() {
return _x;
}();
self.y = function() {
return _y;
}();
return self;
}
return constructor();
}
Which of course isn’t really immutable, but if it were either 1) well-documented that the properties ‘x’ and ‘y’ are getter-functions or 2) threw some kind of alert when validating for immutability then it could act as a de-facto immutable object.
Thoughts?
If you don’t have to worry about older browsers you can look into
Object.defineProperty.Other than that, I don’t think there is much of an option since any function/property on an object can be redefined at any point in JavaScript.