Lioness100
Lioness100

Reputation: 8412

Set a method on all global object prototypes

I was wondering if it was possible to add a function property to all native object prototypes (that being everything on this MDN page).

For example, I could set this simple function to Array.prototype, and it would work fine:

Array.prototype.tap = function (fn) {
  return fn(this);
};

[1, 2, 3, 4, 5].tap(console.log)

But what if I wanted this function to execute on any prototype? For example:

{ name: 'Jonathan', age: 19 }.tap(console.log); // { name: 'Jonathan', age: 19 }
new Map([['1 + 1', 2], ['2 + 2', 4]]).tap(console.log); // Map(2) {"1 + 1" => 2, "2 + 2" => 4}
'Hello World'.tap(console.log); // Hello World
true.tap(console.log); // true
new Date().tap(console.log); // Tue Oct 06 2020 21:09:33 GMT-0400 (Eastern Daylight Time)

Is there any sort of "global prototype" I could assign a function to? Or would I have to manually set it to every native prototype?

Upvotes: 0

Views: 1018

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370979

You can put it on Object.prototype:

Object.prototype.tap = function (fn) {
  return fn(this);
};

[1, 2, 3, 4, 5].tap(console.log)
new Date().tap(console.log);

This will allow nearly any object to access the method. The only exception is objects which don't inherit from Object.prototype (which is rare, and must be done deliberately):

Object.prototype.tap = function (fn) {
  return fn(this);
};

const obj = Object.create(null);
obj.tap(console.log);

But this is just for curiosity's sake. Please don't use this in real code.

Upvotes: 2

Related Questions