Differences between prototype.method vs this.method


#1

Hey guys, could u plz explain me main differences between this examples of code:
function Penguin(name, numLegs) {
this.name = name;
this.numLegs = numLegs;
this.sayName = function(){
console.log("Hi my name is " + this.name);
}
} AND

function Penguin(name, numLegs) {
this.name = name;
this.numLegs = numLegs;
}
Penguin.prototype.sayName = function() {
console.log("Hi my name is " + this.name);
}


#2

the first one, you simply create a method inside an object

the second one, you first create an object, then use prototype to add a method to your object later


#3

By using prototype, every Penguin instance will inherit sayName function. If you use this, the function will be declared every time new Penguin is created - it's inefficient. However, using this inside constructor allows you to use local (private) variables declared inside construcor. Here you can read all about it.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.