Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The Benefits of JavaScript Prototype

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!

like image 991
lucas1000001 Avatar asked Aug 11 '10 20:08

lucas1000001


People also ask

Should you use prototype in JavaScript?

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.

Why would you use a prototype?

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.

What does prototype mean in JS?

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.

Should I use prototype or class 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.


1 Answers

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); }
like image 157
palswim Avatar answered Oct 15 '22 17:10

palswim