ECMAscript 262-5 proposed the option of having getters and setters on objects officially defined by the specification. You can configure them either directly in the object literal
var foo = { get bar() { return "foo"; } };
or using Object.defineProperty()
var foo = { }; Object.defineProperty(foo, 'bar', { get: function() { return "foo"; } });
However, the problem remains the same. Overwriting a property will unreasonably overwrite it. What you can do is use prototype chain objects to get properties.
var foo = { }; foo.bar = 42; Object.defineProperty(Object.getPrototypeOf( foo ), 'bar', { get: function() { return 'overwritten'; }, configurable: true }); console.log( foo.bar );
jAndy source share