object - Javascript, instance property junk -


in javascript code below create 2 instances of person (p1 , p2).

when changing name of p1, name of p1 changed (and not name of p2). expect.

but when changing p1.sizes.width , checking value of p2.sizes.width, appears p1.sizes.width equal p2.sizes.width.

why?

var person = {   name: '',   sizes: {width: {type:'size', value:undefined}, height: {type:'size', value:undefined}} }  var p1 = object.create(person); var p2 = object.create(person);  p1.name = "alice"; p2.name = "bob";  console.log(p1.name === "alice") // true console.log(p2.name === "bob") // true  p1.sizes.width=20;  console.log(p1.sizes.width === 20) // true console.log(p2.sizes.width === 20) // true (but had expected false...?!) 

you're creating delegation chain same object opposed instantiating new versions of person each time. means when jit compiler looks property sizes (which undefined on p1/p2 object) - goes next object in delegation chain - in case person - modify .sizes.width. reason why doesn't matter on names property overwriting property on individual instance. if want separate instantiations use new keyword ie:

var person = function(){   this.name = '',   this.sizes = {width: {type:'size', value:undefined}, height: {type:'size', value:undefined}} }  var p1 = new person(); var p2 = new person();  p1.name = "alice"; p2.name = "bob";  console.log(p1.name === "alice") // true console.log(p2.name === "bob") // true  p1.sizes.width=20;  console.log(p1.sizes.width === 20) // true console.log(p2.sizes.width === 20) // false 

you can read more here , here


Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

json - Gson().fromJson(jsonResult, Myobject.class) return values in 0's -