ibrahim morsi blacktiger ibrahim morsi blacktiger - 3 months ago 6
Javascript Question

what is the benefit of using prototype after creating constructor function?

If you have a constructor function like

var SomeClass = function(){
this.a= "";
this.b= "";
}


then let's say you add another method using prototype

SomeClass.prototype.fn = function fn(){
console.log(this.a);
};


Why use
prototype
where you can just add this method to your constructor
function?

Answer

There are a few benefits:

  1. It creates one fn function, reused by all objects created with that constructor; this is more memory-efficient than a separate function on every object.

  2. Having the objects keep a dynamic link to their prototype means when you add methods to the prototype, they're available to objects that already exist.

  3. Having just one function all relevant objects reuse means you can update that function if necessary at runtime, in just one place, and have the updated function used by all relevant objects, even ones that already exist.

  4. Having it available on the constructor's prototype property means it can be used on other objects, not created via the constructor; this is frequently used to good effect, such as:

    Array.prototype.forEach.call(
        document.querySelectorAll("div"),
        function(div) {
            // ...
        }
    );
    
Comments