They are definitely not equivalent. I am writing this answer to explain in more detail why this matters.
var p = {};
Creates an object that inherits properties and methods from Object .
var p2 = Object.create(null);
Creates an object that does not inherit anything.
If you use the object as a map, and you create the object using method 1 above, then you should be especially careful when performing a search on the map. Since the properties and methods from Object are inherited, your code may work if there are keys on the map that you never inserted. For example, if you performed a search in toString , you will find a function, even if you never set this value. You can get around this as follows:
if (Object.prototype.hasOwnProperty.call(p, 'toString')) {
Note that it is great to assign something to p.toString , it will simply override the inherited toString function to p .
Note that you cannot just do p.hasOwnProperty('toString') , because you can insert the "hasOwnProperty" key into p , so we force it to use the implementation in Object .
On the other hand, if you use method 2 above, you donโt have to worry about things from Object appearing on the map.
You cannot check for a property with a simple if as follows:
// Unreliable: if (p[someKey]) { // ... }
The value can be an empty string, it can be false or null , or undefined , or 0 , or NaN , etc. To check if a property exists at all, you still need to use Object.prototype.hasOwnProperty.call(p, someKey) .
doug65536 Jan 12 '14 at 19:29 2014-01-12 19:29
source share