'Object.create({}): Is is a good practice?
I've been talking to some professionals who work with JavaScript in a company, and I've been told that it isn't a good practice to create an object instance using either new
or the global object {}
, even if I want an empty object, like this:
var wrong1 = new Object();
var wrong2 = {};
The correct way, according to them and the company's standards, is to create it like this:
var correct = Object.create({});
Passing an empty object as the prototype of an empty object seems rather over-engineered, and maybe even purposeless.
Can someone provide me an answer as to why this is recommended, or if it isn't, why not? (possible pros. and cons.)
Solution 1:[1]
The object literal will create an object with the following prototype chain.
Object.prototype -> {}
The literal syntax is heavily optimized by most engines because it's such a common pattern.
To compare, Object.create({})
creates an object with a longer prototype chain.
Object.prototype -> {} -> {}
The instance (on the far right) has a prototype of {}
, which as seen before already has a prototype of Object.prototype
.
Object.create
is a very useful function for creating objects with custom prototypes and it doesn't suffer from the same problems as new
. However, we don't need it here because {}
already creates an object with a shorter prototype chain.
I don't know why anyone would think that adding this extra layer of indirection (and performance loss) was a "best practice".
If anything, I'd say that the literal syntax was safer—as there's no way for {}
to be accidentally/maliciously redefined, unlike Object
which can be shadowed.
var Object = 3;
// ...
Object.create({}) // TypeError: Object.create is not a function(...)
Of course, this doesn't mean you should never use Object
, but in this case I think that {}
is the simplest tool for the job and as a result, it has the best performance too.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |