Extending constructors with frozen instances

# Axel Rauschmayer (14 years ago)

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.