1

What's the difference between using or not using prototype? They apparently do the same.

With prototype:

function poligon(angles){
     this.angles = angles;
}
poligon.prototype.color = function(){ return "blue"; }

var mypol = new poligon(14);

alert(mypol.color());

Without prototype:

function poligon(angles){
     this.angles = angles;
}
poligon.color = function(){ return "blue"; }

var mypol = new poligon(12);

alert(poligon.color());

What does it really mean adding a "color" object with prototype and without it?

user1883212
  • 7,539
  • 11
  • 46
  • 82
  • A previous post explains prototype pretty good http://stackoverflow.com/questions/12064104/prototype-keyword-in-javascript – AurA Apr 17 '13 at 09:14

2 Answers2

2

Yes, this is not always clear when introduced to javascript prototypes.

If you add a method to the prototype, every single object inheriting from that prototype will have this function from that point on. In this case, your class/function 'poligon' is probably the only class inheriting from this prototype.

The difference comes when you declare a new type, 'rectangle' for example, for which you declare rectangle.prototype = poligon.prototype;. Now your rectangle class will inherit all methods declared in the poligon prototype, which wouldn't be the case if you just added the method to 'poligon'.

Inheritance works differently in javascript, and is at times very confusing when coming from a classic OOP language.

Joachim VR
  • 2,320
  • 1
  • 15
  • 24
1

By using prototypes like you do there is no difference, but the prototype comes in handy when you're creating new objects derived from your Poligon object.

Poligon.print = function() {};
new Poligon().print(); // Has no method print

Poligon.prototype.print = function() {};
new Poligon().print(); // Tah dah!
Jan Jongboom
  • 26,598
  • 9
  • 83
  • 120