How does the array property work in JS object

  • A+

For the following code, why the propB of myObj is updated? And why test.childObj doesn't have the own property propB?

var myObj = { propA: '', propB: [] } var fatherObj = {     childObj: null,     init: function() {         this.childObj = Object.create(myObj);         this.childObj.propA = 'A';         this.childObj.propB.push(2);     } }  var test = Object.create(fatherObj); test.init();  console.log(myObj.propB.length); console.log(test.childObj.hasOwnProperty('propA')); console.log(test.childObj.hasOwnProperty('propB'));


Using Object.create you do not copy an object, but you create a new object that inherits the passed one:

  this.childObj { } ->  myObj { propA: "", propB: [] } 

Now when you get a property, it gets looked up in the inheritance chain. As it can't be found in the child object, it gets looked up in myObj. That is usually not a problem, as setting an objects property directly sets it on the object itself without using the inheritance chain, therefore this:

  this.childObj.propA += "test"; 

looks up propA on myObj but sets propA on the childObj. With reference types however, you do not rewrite the property, therefore this:


looks up propB in myObj, and pushes to that, the result is:

 this.childObj { propA: "test" } ->  myObj { propA: "", propB: [1] } 

To resolve that, the childObj has to have its own propB array:

 this.childObj.propB = this.childObj.propB.slice(); 

That results in:

 this.childObj { propA: "test", propB: [1] } ->  myObj { propA: "", propB: [1] } 

and now pushing to propB pushes to the array in childObj.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: