If it's defined on the prototype, any instance of FooController will "inherit" the bar
method because it's in the instance's prototype chain. Only 1 function is defined and in memory using this technique.
If you define using this.foo = function
, you're adding the function directly to the instance as a property of that instance. This means that you will have 1 function in memory per instance of the controller.
function FooController {}
FooController.prototype.hello = function() {
console.log("world");
};
Create an instance and check the prototype's value
var c = new FooController();
c.hello(); // "world"
This is as expected, but let's define a hello
method directly on the c
instance
c.hello = function() { console.log("cats"); };
c.hello(); // "cats"
We can still call the prototype method directly
c.prototype.hello.call(c); // "world"
Or we can delete
the hello
property on the c
instance
delete c.hello;
Now let's call our function again
c.hello; // "world"
It's back to using the prototype's method !