What is a sample scenario where you need prototyped functions and internal functions?
Let there be two instances foo
(in fact, since it is a constructor, it must be capitalized;))
var myFoo1 = new foo();
var myFoo2 = new foo();
In the first case, it myFunction
is in the prototype foo
, so there is only one instance of this function in memory. myFoo1
and myFoo2
can use this function for their own purposes, as they call it with this
.
In the second case, a new copy is created myFunction
each time an instance is created foo
. There will be multiple instances in memory.
So ... it saves memory if you put methods (or read-only member variables) in the prototype, or just other general stuff. On the other hand, it also slows down the search for an element a bit - the function is not directly in the object, but one step up its prototype chain.
source to share
A good example of where this makes a huge difference is when you need to instantiate a lot of "foo" objects. The prototype solution will be much faster and more efficient than the second one.
The reason it makes a huge difference in this case is because in the second example, you create a new function for each new instance, and in the first, all objects have the same function.
A good example of a real thing that should use prototype based inheritance for performance is a jQuery like library. In a non-trivial web application, you can easily get 2000 object instances. Imagine that each of these objects had to have their own function and not share them.
source to share
There is never any need to do this, but there are some advantages as well as disadvantages.
-
Benefit: The prototyped function is shared among all objects created from the constructor
foo
. -
Disadvantage: The prototyped function does not have direct access to variables in the immediate variable scope of constructor-constructors
foo
.
Instead of using the constructor's prototype
constructor, you can also directly assign a 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 that it myFunction
obviously won't be able to access variables on the design surface.