Daniel Herr Daniel Herr - 3 months ago 22
Javascript Question

Inherit Method to All Objects Except Primitives

I want to add a method that is capable of working on all objects. Preferably it should not exist on primitives (number, boolean, string, symbol), on which it cannot work.

Is this possible, and if so, how?

Using Object.prototype does not work because the primitive types inherit from Object.

Answer

You can set the function on the prototype of Object, then set the corresponding member on the prototypes of the constructors where you don't want it to undefined:

Object.prototype.foo = function() { alert("foo"); };
Number.prototype.foo = undefined;
var x = {};
var y = 10;
x.foo(); // works
y.foo(); // TypeError: y.foo is not a function

I don't know why you're doing this, and it seems like a code smell, but there you go.