Imagine a scenario where an object is created elsewhere and passed to my module. It could have been generated on the server in node.js
, or perhaps in a different module where it was then serialized using JSON.stringify()
for transmission (especially if it originated from the server). I need to ensure that a specific property of this object remains immutable:
var foo = {};
Object.defineProperty(foo, 'bar', {
value: 'bar',
writeable: false,
enumerable: true
});
console.log(foo.bar); //bar
foo.bar = 'foo'; //fails, throws err in strict
console.log(foo.bar); //still bar
var fii = JSON.parse(JSON.stringify(foo));
console.log(fii.bar); //still bar
fii.bar = 'foo'; //succeeds
console.log(fii.bar); //now foo
Is there a way to preserve this metadata to ensure the immutability of the bar
property without sending it separately?