Preventing instance extension
Object.getPrototypeOf(this) === Point.prototype <=> this instanceof Point
And I don't understand your problem >_ <
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
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.
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.
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
Variant 2: allows subtyping, not very pretty.