The main difference is in the way it is used, and the dangers associated.
The first one forces you to use new
when you want to create a new object. The syntax is fairly ugly (SomeConstructor.prototype.method
), and it bears one major flaw: calling a constructor which adds properties (this.name = nameParam
...) without new
will apply the construction to the global object. The behaviour of the constructor is weird (create new object which delegates to SomeConstructor.prototype
, then apply the constructor to the new object, then if the constructor returns something replace the object by the something). Plus, in your example, foo
itself is not usable, you have to create a new object in order to access its functionalities.
The second one, Object.create
, doesn't force you to use any syntoxic quirk. You don't have the global pollution risk. The object foo
has functionalities that can already be used without creating a new object, and bar
will simply borrow these functionalities. This kind of pattern can also make it easier to implement factories (without new
s to replace everywhere) and object pools if needed.
Eric Eliott talks about it very well, and Kyle Simpson wrote a whole book about prototype delegation!
Now, here's how the lookup happens:
- With the constructor, the lookup is done on
Constructor.prototype
(not the actual internal prototype of the constructor, but its prototype
property. If you find it confusing, congratulations, you are human). Additional properties are set in the constructor function. foo
itself is not used for the lookup, foo.prototype
(again, not the same as foo.__proto__
which points to Function) is the one used for it.
- With
Object.create
the lookup is done on the object itself (foo
). There's no prototype
non-prototype property on the object.
There's very funny diagrams on this page of Kyle Simpson's book which explain the thing further.
More on new
in this question: Is JavaScript's "new" keyword considered harmful?