1

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

I am trying to understand object in JavaScript. Now I see a lot of different uses of object, and I can not tell them apart.

For starters, the biggest thing I want to know is what the difference is between these two

Something.prototype.else = function(){
  return 6;
}

And

Something.else = function(){
  return 6;
}

Both look different, but they are used in the same way, or am I mistaken.

Community
  • 1
  • 1
Saif Bechan
  • 16,551
  • 23
  • 83
  • 125
  • 2
    there should be a zillion sites explaining the difference, have a go with google, read some bits ( maybe you'll learn more than just this piece of info ) – Poelinca Dorin Nov 18 '11 at 08:53
  • similar question: http://stackoverflow.com/q/5912497/69820 –  Nov 18 '11 at 08:54
  • Yes sorry for asking this. I will have a better look next time. – Saif Bechan Nov 18 '11 at 08:57
  • 1
    @PoelincaDorin Simply suggesting to search [isn't helpful](http://meta.stackexchange.com/questions/8724/how-should-we-deal-with-google-questions). If you know of a resource related to the question, please share it. – Jonathan Lonowski Nov 18 '11 at 10:05
  • @SaifBechan Check out http://stackoverflow.com/questions/1635116/javascript-class-method-vs-class-prototype-method. – Jonathan Lonowski Nov 18 '11 at 10:13
  • @JonathanLonowski i understand how we should deal with the problem now, however what should i do in these kind of situations where the answer is realy simple and there are tons of resources explaining it flag it whont help and close it whont help either . I understand that a question needs and answer so that google searches will lead here but there are allready google searches that deal with this exact question way better than the answers found here so in the end we're populating google searches with poor answers, p.s. we need to move this conversation to meta – Poelinca Dorin Nov 18 '11 at 10:36
  • I flagged this for moderation attention. hope it gets deleted soon – Saif Bechan Nov 18 '11 at 16:48

2 Answers2

4

If you are familiar with other programming languages you can consider the second one to be a static method.

The first one you need an instance of the object in order to use it:

var x = new Something();
x.else();

The second one you do not need an instance in order to use it:

Something.else();
row1
  • 5,568
  • 3
  • 46
  • 72
  • Another good interview question is "What is the difference between Something, Something() and new Something()" – nponeccop Nov 18 '11 at 08:55
1

It's a good question for an interview for a JavaScript job indeed.

The difference is that Something.else overrides Something.prototype.else. That is, if you have both, Something.else will be used.

The advantage of having prototypes is that a prototype can be shared between many objects to reduce memory usage, make monkey-patching easier and implement prototype-based inheritance.

nponeccop
  • 13,527
  • 1
  • 44
  • 106