Search code examples
javascriptprototyping

What is an example scenario in which you would 'need' prototyped functions vs internal functions?


I'm having difficulty thinking of a real-world scenario in which I would need to do this:

function foo() {};
foo.prototype.myFunction = function() { return something; };

Instead of simply doing this:

function foo() { this.myFunction = function() { return something; } };

Solution

  • Let's have two instances of foo (actually, as it is a constructor, it should be capitalized ;) )

    var myFoo1 = new foo();
    var myFoo2 = new foo();
    

    In the first case, myFunction is in foo's prototype, therefore there exists only one instance of this function in the memory. myFoo1 and myFoo2 can both use this function for their own purposes, as they call it with different this.

    In the second case, a new copy of myFunction is created each time an instance of foo is created. There will be multiple instances in the memory.

    So... it saves memory if you put methods (or read-only member variables, or simply other shared stuff) of objects into the prototype. On the other hand, it also slows the member lookup a bit - the function is not present directly in the object, but one step up its prototype chain.