Search code examples
javascriptiterationgetter-setter

Iterate over an object and replace properties with setters and getters


I want to be able to have a function that will replace all of an objects properties with a setter and getter.

function myFunction(obj){
var private={};
for(var i in obj){
if(obj.hasOwnProperty(Ii){
private[i]=obj[i]
delete obj[i]
Object.defineProperty(obj, i, {
set:(function(i){return function(val){private[i]=val}})(i),
set:(function(i){return function(){return private[i]}})(i)
})}
}
return obj
}

Would this work or should I use a different method to iterate over the object, could this style of storing the data in a seperate object also cause issues.


Solution

  • Storing the data in a separate object is fine.

    I would simplify the code a bit by using Object.keys, assuming that you didn't really mean to replace inherited properties (for-in enumerates both "own" and inherited properties; Object.keys just gives you an array of "own" enumerable properties):

    function myFunction(obj){
        var private = {};
        Object.keys(obj).forEach(function(key) {
            private[key] = obj[key];
            // No need for the `delete`
            Object.defineProperty(obj, key, {
                set: function(value) {
                    private[key] = value;
                },
                get: function() {
                    return private[key];
                },
                enumerable: true,
                configurable: true // Or leave it off if you don't want the
                                   // property reconfigured
            });
        });
        return obj;
    }
    

    Notes:

    • By using the forEach callback, we make the get/set function closures over key and so can avoid creating temporary wrapper functions.
    • enumerable defaults to false; I'm assuming you don't want to change the enumerability of the properties, so I've added enumerable: true
    • You had set twice, rather than get and set