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

StackOverflow https://stackoverflow.com/questions/10037952

  •  29-05-2021
  •  | 
  •  

Question

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; } };
Was it helpful?

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.

OTHER TIPS

A good example of where it makes a huge difference is when you need to instantiate a lot of "foo" object. The prototype based solution will be a lot faster and efficient than the second one.

The reason it makes a huge difference in that case, is that in the second example you are creating a new function for every new instance and in the first one all the object share the same function.

A good example of real-world thing that needs to use prototype based inheritance for performance are library like jQuery. In non-trivial web application you can easily end up having 2000 and more object instance created. Imagine if each of those object had to have their own function and not share them.

There's never a need to do it, but there are some advantages, as well as disadvantages.

  • An advantage: the prototyped function is shared among all objects created from the foo constructor.

  • A disadvantage: the prototyped function has no direct access to variables in the immediate variable scope of the foo constructor invocations.


Instead of using the prototype of the constructor, it's also possible to do a direct assignment of the function in the constructor without creating new functions for each object.

You can do it like this...

var foo = (function() {

    var myFunction = function() { return something; };

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

})();

This has the same limitation of prototyped functions in that the myFunction will obviously not be able to access variables in the scope of the constructor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top