Whats the difference between defining the method "area" as a property of "this" instead of "prototype"?
//console.clear()
function Rectangle(w, h)
{
this.width = w;
this.height = h;
this.area = function( ) { return this.width * this.height; }
}
var r = new Rectangle(2, 3);
var a = r.area( );
//console.log(a)
function Square(s)
{
this.side= s;
}
Square.prototype.area = function(){return this.side * this.side; }
var r = new Square(2);
var a = r.area( );
//console.log(a)
In JavaScript - The definitive guide
in the section Prototypes and Inheritance
of Chapter 9 , part 1
, the author says that defining the method "area" inside the prototype object is beneficial, but his explanation wasn't really understandable:
"..the area of every single Rectangle object always refers to the same function (someone might change it, of course, but you usually intend the methods of an object to be constant). It is inefficient to use regular properties for methods that are intended to be shared by all objects of the same class (that is, all objects created with the same constructor)."
I know this question almost looks like this one, but it is not.