Bad Code
Bad Code

Reputation: 116

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.

Upvotes: 3

Views: 45

Answers (2)

Mark
Mark

Reputation: 92450

You have to be a little careful about declaring variables in Javascript. Your current code creates a global variable ele (it's added as a property of the window object) because you haven't declared it with var, let etc.

For example:

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

console.log("ele is visible outside: ", ele)
console.log("ele is same as window.ele: ", ele === window.ele)

The answer to your main questions is no, instance variables are not stored on the functions prototype. Calling new b() will create a new object that has properties you assigned using this. That object is linked to the function's prototype through prototypical inheritance:

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

console.log("b.prototype.var?", b.prototype.var)
console.log("a.var?", a.var)

Because of prototype chaining if you assign something to b's prototype it will be available to instances of b (so long as they don't already have the same property of their own).

function b() {
  this.var = 20;
}
b.prototype.testArray = [1, 2, 3] 

let a = new b()
let c = new b()

console.log(a.test, c.test)
console.log("They point to the same object?", a.test === c.test)

Upvotes: 2

justMe
justMe

Reputation: 664

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.

Upvotes: 2

Related Questions