Consider the following to JavaScript snippets:
function foo() {
this.bar = function() { };
}
// or... (if we used an empty constructor function)
foo.prototype.bar = function() { };
What’s the difference when I do this:
function baz() {
}
baz.prototype = new foo();
In both cases baz ends up having a member bar but what’s the difference? Why would I do this in different places?
The difference is where in the prototype chain the property is located.
Assuming we have
f = new foo();andb = new baz(). Then we have the following situations:Definition of
foowithout using a prototype:baris a property of the object itself (f.howOwnProperty('bar')returnstrue).If you assign the property to the prototype instead, the situation is:
fdoes not have its own propertybar, but the property is shared with all otherfooinstances.Similar for the second snippet, which results either in
or
Why do you want to do this?
It’s mainly about structure and not wasting memory. You can add functions to an object in a constructor function:
but this also means that each instance of
Foohas it’s own function, that is,f1.bar === f2.barisfalse, although both functions are doing the exact same thing.Using the prototype gives you a clean way to separate properties common to all instances and instance-specific ones.
In the end, it is “just” inheritance which is one concept in software development (like aggregation) and can be used wherever it makes sense. Your second snippet basically means that a
bazis-afoo, so abazinstance, in addition to its own properties, has the same properties as afooinstance (inherited).