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.
In most cases they are essentially the same, but the second version saves memory because there is only one instance of the function instead of a separate function for each object.
To answer your question simply, there is no real difference. Straight from the MDN web docs definition: JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance.
'Prototype' helps remove code redundancy which helps boost your app's performance. If you are seeking to optimize resources or memory on your application, you should use prototype .
prototype is a property of a Function object. It is the prototype of objects constructed by that function. __proto__ is an internal property of an object, pointing to its prototype.
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 say this.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 all Rectangle
s. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With