Isn't that common practice?
Only when your're creating subclasses (constructor functions with prototypes inheriting from other prototypes).
But that's not the purpose of this code, which basically Object.create
. It takes the part of creating the object which inherits from another object, nothing else. The F
constructor function is only intermediate and not supposed to be exposed.
F.prototype = o;
why he doesn't he do F.prototype.constructor = F
?
Because that would change o
itself. The aim is only to create a new object. Notice that it returns an instance of the intermediate constructor, not the constructor itself.
Where would the constructor
be set (if needed)? On the new object that is instantiated by object
:
function inherit(chd, par) {
chd.prototype = object(par.prototype);
chd.prototype.constructor = chd;
}
function Foo() {}
function Bar() {}
inherit(Foo, Bar);
/* Because of overwriting `constructor`: */
Foo.prototype.constructor === Foo
(new Foo).constructor === Foo
/* Because of the prototype chain: */
new Foo instanceof Bar // true, because
Foo.prototype instanceof Bar // true