2

I have an issue when I want to add a method to Object class in JavaScript. I don't know the different between Object.myMethod and Object.prototype.myMethod.

Object.myMethod = function (){};

Object.prototype.myMethod = function (){};

Can anyone help me out

thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
hoatv
  • 21
  • 2
  • Just google [Javascript prototype inheritance explained](http://www.google.com.au/search?q=javascript+prototype+inheritance+explained&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-GB:official&client=firefox-a&safe=active), then come back with questions. – RobG Oct 19 '11 at 03:33
  • Possible duplicate of [Javascript: prototype inheritance](http://stackoverflow.com/questions/892595/javascript-prototype-inheritance) – RobG Oct 19 '11 at 03:34
  • possible duplicate of [JavaScript: Class.method vs. Class.prototype.method](http://stackoverflow.com/questions/1635116/javascript-class-method-vs-class-prototype-method) – Rob W Dec 27 '11 at 15:35

2 Answers2

6

Object is the constructor function. Like all functions in JavaScript, it is an object, and you can attach properties to it. Those properties can be functions. So doing

Object.myMethod = function () { };

attaches myMethod to the Object constructor function, which means you can call it like so:

Object.myMethod();

Object.prototype is the prototype used as a base for all JavaScript objects. It is itself an object, and so again you can attach properties to it. The difference is, properties attached to the prototype get prototypally-inherited by all objects via their internal [[Prototype]] reference, so something like this is possible:

Object.prototype.myMethod = function () { };

var obj = {};
obj.myMethod();

var otherObj = { something: "else" };
otherObj.myMethod();

var objectViaConstructor = new Object();
objectViaConstructor.myMethod();

var instanceOfSomethingThatInheritsFromObject = new XMLHttpRequest();
instanceOfSomethingThatInheritsFromObject.myMethod();

Note that most of the above applies for arbitrary constructor functions, with the exception that you do not get a special object literal syntax, and Object is special in that everything (up to and including the example XMLHttpRequest) inherits from it. So:

function MyConstructor() { }
MyConstructor.staticMethod = function () { };
MyConstructor.prototype.method = function () { };

MyConstructor.staticMethod();

var myConstructed = new MyConstructor();
myConstructed.method();
Domenic
  • 110,262
  • 41
  • 219
  • 271
1

Object.myMethod is a method on a single object, it's similar to a Static Method in languages with classical OOP.

Object.prototype.myMethod is a method that will exist on all instances of an object, similar to an Instance Method (sometimes just called a Method, vs a Static Method) in languages with classical OOP.

If you're creating instances of your Object (i.e. new MyClass()) then use a prototype method.

Stephen
  • 18,597
  • 4
  • 32
  • 33