Say we have a code example like this :
var obj1={ prop:1 };
var obj2=Object.create(obj1);
obj2.prop=2;
console.log(obj1.prop);
Here we will have output as 1
because in the child object obj2
the property prop
will be shadowed. However when I do this :
var obj1={ prop:{subProp:1} };
var obj2=Object.create(obj1);
obj2.prop.subProp=2;
console.log(obj1.prop.subProp);
Here surprisingly I find that the output is 2
despite the fact that the value is being changed on the child object. Why isn't variable shadowing taking place here. In other words why isin't a new property called prop
being created on obj2
and why is the prop
of the parent object ( obj1
) being manipulated here ?
EDIT : If I do the following
var obj1={ prop:1 };
var obj2=Object.create(obj1);
var isPresent=obj2.hasOwnProperty('prop');
console.log(isPresent);
here output will be false. However :
var obj1={ prop:1 };
var obj2=Object.create(obj1);
var isPresent=obj2.hasOwnProperty('prop');
console.log(isPresent);
obj2.prop=2;
isPresent=obj2.hasOwnProperty('prop');
console.log(isPresent);
Here as you can see after the line obj2.prop=2
the output is true. That is also confusing me.