I added a function to Object.prototype using Object.prototype.func = function () {...} but when I try to call it using Object.func() it throws an error that it is not defined in Object.
2 Answers
Everything in JavaScript is an object and inherits from Object (including Object). If there's a property on Object.prototype then EVERYTHING can access it because it is in everything's prototype.
3 Comments
Esailija
Note that the primitives weren't objects, but were silently converted to a new object to call the method and the object was then discarded
geeko
@Adam does this include Object() itself? I want to do Object.func()
Esailija
@geeko the jsfiddle has
Object.func() right there at the end, you are doing something differently. Also see jsfiddle.net/9WjBrSeems to be working fine for me (from node REPL):
Object.prototype.something = function() { console.log("Something!"); }
[Function]
> b = new Ob
Object
Object
> b = new Object()
{}
> b.something()
Something!
2 Comments
geeko
you are creating a new object using Object() but I'm trying to call my func from within Object() itself like Object.func() but it is not working
Mike Rossi
You mean like this:
> Object.prototype.someFunc = function() { console.log("some function"); } > Object.someFunc(); > some function. Again, this works just fine.
Objectalso inherits fromObject.prototype.