Search code examples
javascriptprototype

Where will function below statements be stored in a prototype of that function


   function b(){
     this.var = 20;
     ele = 10;
   }
   let a = new b()

Because i can see neither ele nor this.var is stored in the b.prototype constructor.


Solution

  • If you want to store a property on a prototype just add it via "prototype"

    function b(){
     this.var = 20;  
    }
    b.prototype.ele = 10;
    
    let a = new b();
    

    You will be able to access it directly through the created instance "a"

    a.ele //will return 10
    

    Remember that prototype is a single object, so every instance created with the same constructor will link to a single prototype.

    Every instance has it's own scope, but shares a single prototype. It is important from performance perspective.