javascriptlazy-evaluation

How can I lazy evaluate fields on a javascript object?


I am wondering if it is possible to do something like the following:

var obj = {
   counter: (function(){
                if(!this.val){ this.val = 0; }
                this.val += 1;
                return this.val;
            })();
};

console.log(obj.counter); //should output 1
console.log(obj.counter); //should output 2
console.log(obj.counter); //should output 3
...

Is there a way to get a field from an object like this such that it re-evaluates a function each time it is accessed?


Solution

  • You can use a getter:

    var obj = {};
    Object.defineProperty(obj,"counter",{
        get: function() {
            this.val = this.val || 0;
            this.val++;
            return this.val;
        }
    });
    
    console.log(obj.counter); // 1
    console.log(obj.counter); // 2
    console.log(obj.counter); // 3