2

Possible Duplicate:
How does JavaScript .prototype work?

What is the use of prototype property when properties can be added to object even without it?

var o = {};

o.x = 5;
o.y = test;

test = new function(){ alert("hello"); };
Community
  • 1
  • 1
sushil bharwani
  • 29,685
  • 30
  • 94
  • 128
  • Your last line does not make much sense. It has nothing to do with prototype, and you don't use `new function() { }`. – pimvdb Aug 23 '11 at 17:32
  • @pimvdb - you actually can - it's an anonymous, immediately invoked constructor function. – Sean Vieira Aug 23 '11 at 17:33
  • -1 because this question is asked soooo much – hvgotcodes Aug 23 '11 at 17:33
  • @hvgotcodes i am not asking what is prototypal inheritance. I just saw that i can add properties to a object like this also. So the question was how it is different from doing it with prototype than. – sushil bharwani Aug 23 '11 at 17:38
  • @Moreover the link you have posted is having different view from what i want to understand. – sushil bharwani Aug 23 '11 at 17:40
  • Please understand the question before closing it. I am not asking the definitions. – sushil bharwani Aug 23 '11 at 17:43
  • SO is changing .. there are less people answering more people closing and suggesting to check some other question as a possible duplicate. It looks like its converting more into a search engine again. Loosing its beauty of newbies to ask learn and grow. If it has to be just search google is better. – sushil bharwani Aug 23 '11 at 17:51

2 Answers2

6

Adding a method / property to a prototype is adding it to all objects with that prototype in their prototype chain.

Your code is adding a method/property to a single instance.

To make use of prototypes you need to create your objects using new. If you create an object via an object literal you aren't specifying the prototype for the object, as far as I know you can't set the prototype retrospectively.

James Gaunt
  • 14,631
  • 2
  • 39
  • 57
3

You can use it to create new methods for an existing object.

String.prototype.displayFirstCharacter = function(){
   alert(this.substr(0,1));
}

"my string, first char should be 'm'".displayFirstCharacter();
Maxx
  • 3,925
  • 8
  • 33
  • 38