1 of 20

Object.has()

Jamie Kyle (Discord), Tierney Cyren (Microsoft)

2 of 20

Before

It is very common (especially in library code) to write code like:

3 of 20

After

This proposal simplifies that code to:

4 of 20

Motivation

5 of 20

Existing Libraries

6 of 20

Object.create(null)

Object.create(null) will create an object that does not inherit from Object.prototype, making those methods inaccessible.

7 of 20

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:

8 of 20

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

9 of 20

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 [...]

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty#using_hasownproperty_as_a_property_name

10 of 20

Proposal

This proposal adds a Object.has(object, property) method with the same behavior as calling hasOwnProperty.call(object, property)

11 of 20

12 of 20

FAQs

13 of 20

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.

14 of 20

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)

15 of 20

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.

16 of 20

Details

17 of 20

Specification

This is the same set of steps as hasOwnProperty()

18 of 20

Polyfill

19 of 20

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

20 of 20

References