Extending constructors with frozen instances

Axel Rauschmayer axel at rauschma.de
Sat Nov 12 23:29:01 PST 2011


Repeating an idea from an earlier email, with a suggestion for a fix.

PROBLEM: The following constructor cannot be extended – once its instances are frozen, sub-constructors cannot add their own properties.

    function Point(x, y) {
        this.x = x;
        this.y = y;
        Object.freeze(this);
    }

SOLUTION:

    if (!Function.prototype.sealMaybe) {
        Object.prototype.freezeMaybe = function(inst) {
            // Is `inst` a direct instance of `this`?
            if (Object.getPrototypeOf(inst) === this.prototype) {
                Object.freeze(inst);
            }
        };
    }

EXAMPLE:

    function Point(x, y) {
        this.x = x;
        this.y = y;
        Point.freezeMaybe(this);
    }
    function ColorPoint(x, y, color) {
        Point.call(this, x, y);
        this.color = color;
        ColorPoint.freezeMaybe(this);
    }

Does that make sense? Suggestions for improvements welcome.

-- 
Dr. Axel Rauschmayer
axel at rauschma.de

home: rauschma.de
twitter: twitter.com/rauschma
blog: 2ality.com





More information about the es-discuss mailing list