Welcome, guest | Sign In | My Account | Store | Cart

This is a technique for using a JavaScript getter to calculate the value of an attribute just the first time. Rather than caching the value in some private variable and returning it, you just delete the getter and put the calculated value in its place.

Note: I'd read about this technique ages ago, but forgot the details and had to look-up "delete" for removing the getter. :)

JavaScript, 14 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
mynamespace = {};
(function() {
    //...

    this.__defineGetter__("my_expensive_attr", function() {
        var value = _do_expensive_calculation();
        /* Replace getter with the calculated value, so only bother checking the first time. */
        delete this.my_expensive_attr;
        this.my_expensive_attr = value;
        return value;
    });
    
    //...
}).apply(mynamespace);
Created by Trent Mick on Fri, 16 Jul 2010 (MIT)
JavaScript recipes (69)
Trent Mick's recipes (28)

Required Modules

  • (none specified)

Other Information and Tasks