3

Possible Duplicate:
JavaScript: Class.method vs. Class.prototype.method

What's the difference between creating a prototype like this:

Date.foo = function(bar) {
    alert(bar);
};

And this:

Date.prototype.foo = function(bar) {
    alert(bar);
};

Why/when should I use either?

Community
  • 1
  • 1
JamesBrownIsDead
  • 345
  • 1
  • 5
  • 9
  • 3
    See: [JavaScript: Class.method vs. Class.prototype.method](http://stackoverflow.com/questions/1635116/javascript-class-method-vs-class-prototype-method) – Christian C. Salvadó Aug 05 '10 at 01:04
  • Sometimes I take it for granted that the question must have been asked before, and close the question blindly. – Anurag Aug 05 '10 at 02:12

1 Answers1

2

in the first example, foo is a constructor method, its like a 'static' method in java. The second is like defining a method foo on a class -- it is scoped to the instance.

you would access the first like

Date.foo()

and the second like

Date d = new Date()
d.foo() 

or in another method on an instance of Date like

this.foo()
hvgotcodes
  • 118,147
  • 33
  • 203
  • 236