Search code examples
javascriptclosuresencapsulationgetter-setter

Minimizing JS getter/setter boilerplate


I am doing closure-oriented object creation with an object that has substantial boilerplate around getter/setter methods. Is there any way to declare these properties as getter/setters without so much repetition?

Currently I have:

var test = function(){
    var width = 10;    
    var height = 10;    
    return {
        width: {get: function(){return width;}, set: function(_){width=_;}},
        height: {get: function(){return height;}, set: function(_){height=_;}},
    }
}

but I want something more like:

var test = function(){
    var width = 10;    
    var height = 10;    
    return {
        width: getset(width)
        height: getset(height),
    }
}

I want to write a function like:

var test = function(){

    var getset = function(val){
        return {
            get: function(){
                console.log('getting');
                return val
            },
            set: function(_){
                console.log('besetted');
                param=_
            },
        }
    }
    var width = 10;    
    var height = 10;    

    return {
        width: getset(width),
        height: getset(height),
    }
}

but this does not work; variables are not overridden properly. What is the best way? Is there a language feature for this?


Solution

  • Here you go:

    var test = function(){
    
        var getset = function(value){
            var val = value;
            return {
                get: function(){
                    console.log('getting');
                    return val
                },
                set: function(_){
                    console.log('besetted');
                    val=_
                },
            }
        }
        var width = 10;
        var height = 10;
    
        return {
            width: getset(width),
            height: getset(height),
        }
    }
    

    A thing to remember with closures - You need a variable that is accessible throughout the scope inside your inner function as well as outside it.