0

I have the Director() function. I have created 2 instances AlfredH and JohnD out of Director() constructor. I did not write the prototype object.

function Director(){
  this.genre = "Thriller";
}

var AlfredH = new Director();
var JohnD = new Director();   

If I check the values of JohnD.constructor; and JohnD.constructor.prototype; I get Director() and Object() respectively.

But, if I add properties to prototype object of Director() like the below:

function Director(){
  this.genre = "Thriller";
}
Director.prototype = {
  noir: true
}; 
var AlfredH = new Director();
var JohnD = new Director();  

and if I check the values of JohnD.constructor; and JohnD.constructor.prototype; I get Object() and Object() respectively. Can anyone explain this behavior? and the same can be extended to the value of JohnD.constructor.prototype.constructor;

krishna
  • 575
  • 2
  • 8
  • 22

1 Answers1

1
var a = {
  value:22;
}

then

var a = {
  somethingelse:0
}

Can you guess what a.value is?

You are overwriting the prototype with another object.

Then add to that that

console.log({}.constructor)===Object;//=true

Maybe try adding it like this:

Director.prototype.noir = true;

Note that anything on the prototype is shared among instances, this is a good thing because it saves memory and instantiate the object quicker with less cpu.

When assigning a new value the value is assigned to the instance but when manipulating the value through functions it affects all instances

Director.prototype.someArray=[];
var d1=new Director();
var d2=new Director();
d1.someArray.push(22);
console.log(d2.someArray);//=[22]

More info on prototype here: https://stackoverflow.com/a/16063711/1641941

Community
  • 1
  • 1
HMR
  • 37,593
  • 24
  • 91
  • 160