Every JavaScript variable is either an object, or it auto-boxes to an object (like string, boolean and number), or it is null or undefined explicitly.
So, it seems like if you want to add a method to all those, you can add a function to Object.prototype which they all extend like Bar suggested.
Object.prototype.myMagic = function(){
console.log("Hello");
};
"thisString".myMagic();
15.13.myMagic();
([]).myMagic();
Note that you are in fact not adding a function to the prototype of a string since a string is a primitive value and doesn't have a prototype, rather, you're adding a method to the prototype of Object - and strings "box" to String
instances (which are objects) that extend Object
and will have this method.
Also note that on ES5 systems, it's possible to create objects that do not extend Object.prototype
via Object.create(null)
, in ES6 it's also possible to modify the prototype of objects via setPrototypeOf
or __proto__
. However, outside those edge cases it should work.