0

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
  • 2
    Can't be. Object also inherits from Object.prototype. Commented Aug 19, 2012 at 14:12
  • You're testing this improperly, because that should work fine. Commented Aug 19, 2012 at 14:15

2 Answers 2

2

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.

http://jsfiddle.net/PxLDu/1/

Sign up to request clarification or add additional context in comments.

3 Comments

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
@Adam does this include Object() itself? I want to do Object.func()
@geeko the jsfiddle has Object.func() right there at the end, you are doing something differently. Also see jsfiddle.net/9WjBr
1

Seems 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

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
You mean like this: > Object.prototype.someFunc = function() { console.log("some function"); } > Object.someFunc(); > some function. Again, this works just fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.