1

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
    });
}
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Kai Sasaki
  • 667
  • 4
  • 13
  • This again looks like the classic loop-closure problem, remember that `var` will be function level not block level. – Paul S. Dec 22 '13 at 14:22
  • possible duplicate of [Javascript closure inside loops - simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Paul S. Dec 22 '13 at 14:23

1 Answers1

2

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);
}
Hallvar Helleseth
  • 1,867
  • 15
  • 17