Adding a method on the constructor will duplicate that method for every instance of the object that created, consuming memory but also granting the method access private variables on the object. Adding a method on the prototype will will not duplicate it for new instances, conserving memory while leaving it available to all instances.
// Constructor with greet method directly on it.
var Person = function (name, age) {
this.name = name;
this.age = age;
var secret = "I'm super happy";
this.greet = function (name) {
return 'Hello ' + name + ' my name is ' + this.name + ' and ' + secret;
};
};
// Constructor with greet method on the prototype
var oPerson = function (name, age) {
this.name = name;
this.age = age;
var secret = "I'm super happy";
};
oPerson.prototype.greet = function (name) {
return 'Hello ' + name + ' my name is ' + this.name;
};
var adrian = new Person('Adrian', 24);
var jason = new oPerson('Jason', 26);
console.log(adrian.greet('John'));
console.log(jason.greet('Tommy'));