6

I have done a fair amount of programming in JavaScript/JQuery.

But I never used "prototype". In fact, I have no clue what it means.

Do you have a practical example when it is useful?

user380719
  • 9,663
  • 15
  • 54
  • 89
  • 5
    It could mean 2 things: a javascript framework, and a javascript method to extend and define objects. The two are completely different. Not sure which one of the two you mean. – Darin Dimitrov Sep 05 '11 at 21:30
  • This question is ambiguous. The lib or the obejcts property? – user278064 Sep 05 '11 at 21:30
  • 1
    You should probably read: [MDN - Introduction to Object-Oriented JavaScript](https://developer.mozilla.org/En/Introduction_to_Object-Oriented_JavaScript). – Felix Kling Sep 05 '11 at 21:36
  • 1
    possible duplicate of [How does JavaScript .prototype work?](http://stackoverflow.com/questions/572897/how-does-javascript-prototype-work), http://stackoverflow.com/questions/7165109/what-is-the-use-of-prototype-property-in-javascript, http://stackoverflow.com/questions/6554207/javascript-prototype – user113716 Sep 05 '11 at 21:39
  • http://stackoverflow.com/questions/6256321/what-does-a-js-functions-prototype-property-used-for – user113716 Sep 05 '11 at 21:45
  • This is a really old post I know, but after reading all links and answers on this page, I still don't know where I'm supposed to actually use it. I'm in the same boat as OP - done JS for quite a few years but no idea as of when I *need* or *require* `.prototype` – ProEvilz May 01 '18 at 18:18

2 Answers2

12

Simplest example:

function Foo() {
    this.bar = function() {
        return 42;
    }
}

Now you can create as many instances of Foo as you want and call bar():

var a = new Foo();
var b = new Foo();

Even though both object have bar() method which is exactly the same in both cases, these are distinct methods. In fact, each new Foo object will have a new copy of this method.

On the other hand:

function Foo() {}
Foo.prototype.bar = function() {
    return 42;
}    

has the same end result but the function is stored only once in object prototype rather than in an object itself. This may be a deal breaker if you create tons of Foo instances and want to save some memory.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
2

Assuming you are asking about Object.prototype,

All objects in JavaScript are descended from Object; all objects inherit methods and properties from Object.prototype, although they may be overridden. For example, other constructors' prototypes override the constructor property and provide their own toString methods. Changes to the Object prototype object are propagated to all objects unless the properties and methods subject to those changes are overridden further along the prototype chain.

Read this and then probably this

Amol Katdare
  • 6,740
  • 2
  • 33
  • 36