I have following code
var createObj = function (prop1, prop2) {
var obj = {
prop1: prop1,
prop2: prop2
}
Object.defineProperty(obj, "prop3", {
get: function () {
return this.prop1 + ' ' + this.prop2;
},
configurable: true
});
return obj;
}
var createSecObj = function () {
var obj = createObj("prop1", "prop2");
var prop3 = obj.prop3;
Object.defineProperty(obj, "prop3", {
get: function () {
return prop3;
}
});
return obj;
}
I am trying to learn how javascript inheritance work.
Lets say an object named myObj is created as
myObj = createSecObj();
Then value of myObj.prop3 is logged to the console as
console.log(myObj.prop3) // "prop1 prop2"
And then myObj.prop1 is changed as "blah" using
myObj.prop1 = "blah"
And again if the myObj.prop3 is logged to the console it results "prop1 prop2". and not "blah prop2".
console.log(myObj.prop3) // results "prop1 prop2", expecting "blah prop2"
Looks like obj.prop3 still refer its parent object. what is the reason for this even it is redefined in child object. Could someone please explain this in detail?