Just adding it to the prototype means every instance of the object will share the same instance of the function.
Given code like this:
function Employee(foo) {
this.foo = foo;
this.name = '';
this.dept = 'general';
}
Employee.prototype.method1 = function(){
console.log('Method1 called');
};
function SalesPerson(foo, bar) {
Employee.call(this, foo);
this.bar = bar;
this.dept = 'sales';
this.quota = 100;
}
SalesPerson.prototype = Object.create(Employee.prototype);
SalesPerson.prototype.constructor = SalesPerson;
SalesPerson.prototype.method2=function() {
console.log('Method 2 called');
}
When you this:
var p = new SalesPerson();
p.method1();
Javascript looks up method1 by roughly doing:
Does p have a property named method1? => No
Does SalesPerson.prototype have a property named method1? => No
Does SalesPerson.prototype.prototype (Which is Employee.prototype) have a property named method1? => Yes
Execute SalesPerson.prototype.prototype.method1.call(p);
So only one instance of the method1 function exists on the Employee.prototype object, it's just reused for the other objects.
You can see this kind of chain if you console.log(p):
If you want to share a single function across multiple objects that are not related via their prototype chain, then you'd do define your function elsewhere and assign a reference to it to each object. This kind of setup is often called a mixin. For example if you had some logging code you wanted to include in each class.
var LoggerInterface = {
log: function(msg){
console.log(msg);
}
};
function Employee(foo) {
this.foo = foo;
this.name = '';
this.dept = 'general';
}
Object.assign(Employee.prototype, LoggerInterface);
Employee.prototype.method1 = function(){
this.log('Method1 called');
};
function Equipment(){
this.name = '';
}
Object.assign(Equipment.prototype, LoggerInterface);
Equipment.prototype.method2 = function(){
this.log('Method2 called');
}
Both Employee and Equipment would have their own independent .log properties, but they would both reference the same underlying function so the function itself isn't duplicated.