Consider the following to JavaScript snippets:
function foo() {
this.bar = function() { };
}
// or... (if we used an empty constructor function)
foo.prot
One big difference is that if you change properties of the prototype those changes will apply to all instances, including those that already exist, whereas if you change a property that was created in the constructor it will only change it for the instance you change it on.
Regarding what some of the other answers said about setting bar
in the constructor resulting in each instance having its own copy of the function: that's true if you have a function expression inside the constructor as shown in the code in the question, but not true if you assign a function reference like this:
function myFunction() {}
function foo() {
this.bar = myFunction;
}
In that case all instances will have a bar
property that refers to the same function - but an individual instance could still have its bar
property assigned to something else without affecting other instances.