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.
Defining a function with
whatever = function() { ... }tends to create what’s called a “closure”, where the function can access local variables of the function that defines it. When you saythis.fn = function() { ... }, each object gets an instance of the function (and a new closure). This is often used to create “private” variables in Javascript, but comes with a cost: each function (in each object) is distinct, and takes up more memory.When you say
Rectangle.prototype.fn = function() { ... }, one instance of the function is shared by allRectangles. This saves memory, and can minimize some memory leaks in browsers that handle closures badly. If you don’t need “private” members, or other such access to the defining function’s local variables, it’s usually a better idea.