Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use "prototype" in JavaScript

Tags:

javascript

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?

like image 229
user380719 Avatar asked Sep 05 '11 21:09

user380719


2 Answers

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.

like image 189
Tomasz Nurkiewicz Avatar answered Nov 15 '22 08:11

Tomasz Nurkiewicz


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

like image 32
Amol Katdare Avatar answered Nov 15 '22 08:11

Amol Katdare