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
[email protected]

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();
    };

_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to