Preventing instance extension

# Axel Rauschmayer (14 years ago)

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);
    }
}
# Xavier MONTILLET (14 years ago)

Object.getPrototypeOf(this) === Point.prototype <=> this instanceof Point

And I don't understand your problem >_ <

# Juan Ignacio Dopazo (14 years ago)

On Fri, Nov 11, 2011 at 4:23 PM, Xavier MONTILLET <xavierm02.net at gmail.com

wrote:

Object.getPrototypeOf(this) === Point.prototype <=> this instanceof Point

Actually, no. this instanceof Point => Object.getPrototypeOf(this) ===

Point.prototype, but not the other way around.

And I don't understand your problem >_ <

The problem is this that when you do prototypical inheritance using

constructors you usually call the superclass before any of the subclass constructor code. So if you just seal(this) in the constructor of the superclass the subclass can't add properties to the object.

function Person(name) { this.name = name; Object.seal(this); console.log(this instanceof Person, Object.getPrototypeOf(this) === Person.prototype); // true false when doing new Pirate() }

function Pirate() { Person.apply(this, arguments); this.eyepatch = true; } Pirate.prototype = Object.create(Person.prototype);

var captain = new Pirate('Blackbeard'); console.log(captain.eyepatch); // undefined

Juan

# Xavier MONTILLET (14 years ago)

And why can't you call the superconstructor at the end? It'd work the exact same except it could overwrite some of the properties you wrote... but since those things would more likely be in prototype, it's not much of an issue.

# Axel Rauschmayer (14 years ago)

And why can't you call the superconstructor at the end? It'd work the exact same except it could overwrite some of the properties you wrote... but since those things would more likely be in prototype, it's not much of an issue.

That is definitely a possibility! It does have one drawback, though: Normally methods in sub-instances expect the super-instance to be completely initialized. So performing the super-initialization last is a bit more risky than performing it first.