简体   繁体   中英

How to make dynamic getter with defineProperty in JavaScript?

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM