Object.has()
Jamie Kyle (Discord), Tierney Cyren (Microsoft)
Before
It is very common (especially in library code) to write code like:
After
This proposal simplifies that code to:
Motivation
Existing Libraries
Object.create(null)
Object.create(null) will create an object that does not inherit from Object.prototype, making those methods inaccessible.
Redefining hasOwnProperty
If you do not directly own every property defined of an object, you can't be 100% certain that calling .hasOwnProperty() is calling the built-in method:
ESLint: no-prototype-builtins
ESLint has a built-in rule for banning use of prototype builtins like hasOwnProperty.��Source: https://eslint.org/docs/rules/no-prototype-builtins
MDN hasOwnProperty advice
The MDN documentation for Object.prototype.hasOwnProperty includes advice not to use it off of the prototype chain directly:
JavaScript does not protect the property name hasOwnProperty; thus, if the possibility exists that an object might have a property with this name, it is necessary to use an external hasOwnProperty to get correct results [...]
Proposal
This proposal adds a Object.has(object, property) method with the same behavior as calling hasOwnProperty.call(object, property)
FAQs
Q: Why not Object.hasOwnProperty(o,p)?
A: Object.hasOwnProperty(property) already exists today because Object itself inherits from Object.prototype so defining a new method with a different signature would be a breaking change.
Q: Why the name “has”?
A: has is a popular name for this function in userland library code (lodash, underscore, etc). It also fills in a hole in the common operations between Object, Map, and Set.
Alternative Options: hasOwn (Discussed in Github Issue #3)
Q: Why match behavior of hasOwnProperty?
A: Most libraries that implement “has(o,p)” in the community are choosing to use hasOwnProperty directly or use the same semantics as hasOwnProperty. There don’t appear to be any popular libraries modifying semantics around enumerability, symbols, etc.
Details
Specification
This is the same set of steps as hasOwnProperty()
Seeking Stage 1
Stage 1 | ✅ introduced to TC39�✅ champion(s) identified�✅ initial explainer | |
Stage 2 | ❓ committee approval�✅ spec text written�❓ spec reviewers selected | |
Stage 3 | ❌ committee approval�❌ spec editor sign off�❌ spec reviewer sign off�❌ received developer/implementer feedback | |
Stage 4 | ❌ committee approval�❌ implement in two browsers�❌ significant in-the-field experience�❌ merge test262 tests | ❌ write test262 tests�❌ prepare ecma262 PR�❌ editor-approved ecma262 PR |
References