I want to define dynamic getter functions with defineProperty
in JavaScript like below. In order to make a readonly function, I want to use defineProperty
. This enables me to throw an Exception in the setter function.
However the getter function won't be functional. I thought that this getter returns the any properties of the obj
dynamically. But it wasn't. It always returns obj["three"]
, last property. Is there any methods to make dynamic getter which returns appropriate property in JavaScript?
var obj = {"one":1, "two":2, "three":3};
var cloned = {};
for (var prop in obj)
{
var getter = makeGetter(prop);
Object.defineProperty(cloned, prop,
{
set: function()
{
throw new UnableRewriteException('original cannot be rewrite');
},
get: function()
{
return obj[prop]
},
enumerable: true
});
}
As @paul-s mentioned you have a problem with a closure inside your loop. A simple fix:
var obj = {"one":1, "two":2, "three":3};
var cloned = {};
function makeReadOnlyProperty(cloned, obj, prop) {
Object.defineProperty(cloned, prop,
{
set: function()
{
throw new UnableRewriteException('original cannot be rewrite');
},
get: function()
{
return obj[prop]
},
enumerable: true
});
}
for (var prop in obj)
{
makeReadOnlyProperty(cloned, obj, prop);
}