Yes. What I am saying is there is a better alternative for that use case. So it's not really much of a use case. Have you ever actually written production code where you used Object.create(null) so you could check property existence without hasOwnProperty?
Yes, I've used Object.create(null) to create dictionary-like objects.
so you could check property existence without hasOwnProperty
That's not the point.
Anyhow, Object.prototype.hasOwnProperty.call(obj, 'foo') really is a mouthful. You know that you can't use this object's hasOwnProperty, right? The text from the example above could contain the word "hasOwnProperty".
> var a = {}
undefined
> a.hasOwnProperty = 1
1
> a.hasOwnProperty('foo')
Uncaught TypeError: a.hasOwnProperty is not a function
Anyway, I feel like we are talking past each other. The property existence use case seems like a bad example to me. And you seem to be saying you’ve never actually used Object.create(null) that way anyway. So what is an actual reason you actually used this pattern?
Because that's so much simpler than using Object.create(null)?
What's going to stop the next person from using methods of this object? That doing that was a mistake will only become apparent when a collision happens.
You are trading issues which are easy to find and immediately pop up for potential issues which only show up if very specific conditions are met.
Failing early is better.
And you seem to be saying you’ve never actually used Object.create(null) that way anyway.
As I said, I've used Object.create(null) for creating dictionary-like objects where the keys are user-supplied. E.g. something like a mime type in an archive format or a request header. Those strings could be anything. Collisions might be deliberate.
So what is an actual reason you actually used this pattern? Also, have you heard of Maps?
It's like Map<string, whatever>, but you can use square brackets. It's a convenient lightweight option if all of your keys are strings.
1
u/inu-no-policemen May 15 '19
E.g. if you want to count words, the text might contain the word "toString".
If you use Object.create(null) the object won't have any keys itself or in its prototype chain.
Always use Object.create(null) if your keys can be any string.