I've been wondering about JavaScript's prototypal nature, and the benefits of it, and have come down to the following list :
1) Inheritance
cat.prototype = animal
2) Memory Efficiency
a.prototype.b = function() {}
var a1 = new a();
var a2 = new a();
Then a1.b and a2.b are essentially the same object, where as :
var a = function() {
this.b = function() {};
}
var a1 = new a();
var a2 = new a();
a1.b and a2.b would be different function objects and take up more memory.
3) Adding methods/fields to multiple, already created, 'out in the wild' objects.
var a = function() {}
var a1 = new a();
var a2 = new a();
a.prototype.b = function() {}
a1.b();
a2.b();
So the question is, are these correct?
... and are there any other benefits I've missed?
Cheers!
There is a clear reason why you should use prototypes when creating classes in JavaScript. They use less memory. When a method is defined using this. methodName a new copy is created every time a new object is instantiated.
The most important advantage of a prototype is that it simulates the real and future product. It can help attract customers to invest in the product before allocating any resources needed for implementation. You can test the design's correctness before it comes into production and you can discover design errors.
The prototype is an object that is associated with every functions and objects by default in JavaScript, where function's prototype property is accessible and modifiable and object's prototype property (aka attribute) is not visible. Every function includes prototype object by default. Prototype in JavaScript.
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.
Those are all correct.
Of course, there are "drawbacks" as well:
No closures
function a() {
var ival = 0;
this.start = function(){ ival = setInterval(function(){ }, 300); }
this.finish = function(){ clearTimeout(ival); }
}
compare to:
function a() {
this.ival = 0;
}
a.prototype.start = function(){ this.ival = setInterval(function(){ }, 300); }
a.prototype.finish = function(){ clearTimeout(this.ival); }
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