Consider the following to JavaScript snippets:
function foo() {
this.bar = function() { };
}
// or... (if we used an empty constructor function)
foo.prot
The difference is where in the prototype chain the property is located.
Assuming we have f = new foo();
and b = new baz()
. Then we have the following situations:
Definition of foo
without using a prototype:
+-----------+ +---------------+
| f | | foo.prototype |
| __proto__-+---->| constructor |
| bar | | |
+-----------+ +---------------+
bar
is a property of the object itself (f.howOwnProperty('bar')
returns true
).
If you assign the property to the prototype instead, the situation is:
+-----------+ +---------------+
| f | | foo.prototype |
| __proto__-+---->| constructor |
| | | bar |
+-----------+ +---------------+
f
does not have its own property bar
, but the property is shared with all other foo
instances.
Similar for the second snippet, which results either in
+-----------+ +---------------+ +---------------+
| b | | foo instance | | foo.prototype |
| __proto__-+---->| __proto__ -+---->| constructor |
| | | bar | | |
+-----------+ +---------------+ +---------------+
or
+-----------+ +---------------+ +---------------+
| b | | foo instance | | foo.prototype |
| __proto__-+---->| __proto__ -+---->| constructor |
| | | | | bar |
+-----------+ +---------------+ +---------------+
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:
function Foo() {
this.bar = function() {};
}
but this also means that each instance of Foo
has it's own function, that is, f1.bar === f2.bar
is false
, 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 baz
is-a foo
, so a baz
instance, in addition to its own properties, has the same properties as a foo
instance (inherited).