Dereference from Prototype Only

Hello all, I am recently feeling that an ability to dereference properties directly from the prototype (an . operator, but which ignores the top level of the prototype chain) could potentially lay the groundwork for great usability improvements in javascript.

Example:

const obj = { a: 1 };
console.log(obj..a);        // undefined
console.log(obj..toString); // [Function: toString]

I've written a proposal, but am new to the TC39 scene; it has no champion currently. I'd love if anyone could give me feedback, impressions, criticism, etc. on my idea. Thanks!

Gershy/proposal-dereference-prototype-only

Welcome @Gershy!

" We unfortunately see {}.hasOwnProperty.call(myObject, ...) used instead"

Object.hasOwn was added to avoid needed to do this: Object.hasOwn() - JavaScript | MDN

"I believe Javascript would benefit greatly from utility methods available on Object.prototype ."

I can not see TC39 ever adding new properties to Object.prototype, the chance of breaking existing code is too high. GitHub - tc39/faq

Hello @aclaymore, thanks! :)

I wonder if there could still be benefit to the proposed operator? It would allow extensions to Object.prototype on an opt-in basis - e.g. I could opt-in by explicitly defining:

Object.defineProperty(Object.prototype, 'map', { enumerable: false, value: fn => {
  const result = {};
  for (const k in this) result[k] = fn(this[k]);
  return result;
}});

const obj = { a: 1, b: 2, c: 3 };
console.log(obj..map(v => v + 1));

Thanks for pointing out that Object.prototype will never change - at the very least, I should refine the argument in my proposal.

No, no property must ever be added to Object.prototype, and since null objects exist that don't inherit from Object.prototype, it wouldn't be appropriate to do so anyways.

To get a method-chaining like flow for plain objects I think GitHub - tc39/proposal-pipeline-operator: A proposal for adding a useful pipe operator to JavaScript. would be the way to achieve this because it doesn't require globally modifying Object.prototype, instead the functions are imported only where used. This reduces 'spooky action at a distance' and makes dead-code-elimination analysis easier.

1 Like