Preventing instance extension

Axel Rauschmayer axel at rauschma.de
Fri Nov 11 11:11:28 PST 2011


Having recently bitten by a mistyped property name (see code underneath signature), I think I might prevent the extension of instances more often. But what is the best way of doing so?

Variant 1: prevents subtyping the constructor

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

Variant 2: allows subtyping, not very pretty.

    function Point(x, y) {
        this.x = x;
        this.y = y;
        if (Object.getPrototypeOf(this) === Point.prototype) {
            Object.seal(this);
        }
    }



-- 
Dr. Axel Rauschmayer
axel at rauschma.de

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


Buggy code:

var action = function() { ... };
var c = new CountDown(1, action);
c.dec(); // action is *not* executed!


    function CountDown(counter, finalAction) {
        this.counter = counter;
        this.finalAction = finalAction;
        // Important! finalAction must always be executed
        this.maybeFire();
    }
    CountDown.prototype.maybeFire = function () {
        if (this.counter <= 0 && this.finalAction) {
            this.finalAction();
        }
    };
    CountDown.prototype.dec = function () {
        this.conter--; // typo!
        this.maybeFire();
    };



More information about the es-discuss mailing list