1

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?

0

1 Answer 1

4

Looks like obj.prop3 still refer its parent object. what is the reason for this even it is redefined in child object.

The issue has nothing to do with inheritance. The issue is that you overwrote prop3 with

var prop3 = obj.prop3; // var prop3 = "prop1 prop2";

Object.defineProperty(obj, "prop3", {
   get: function () {
       return prop3; // will always return "prop1 prop2"
   }
});

obj.prop3 will always return the value of the variable prop3. The value of the variable prop3 cannot be changed anymore throughout the application, and at the moment it was created, its value is "prop1 prop2".

It's unclear to me what you are trying to achieve here, so I can't really suggest a solution. If you want to get "blah prop2" then simply remove the above lines from your code.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the answer :) i want to re use the code createObj , prop3 without re writing it as return this.prop1 + ' ' + this.prop2; inside createSecObj.prop3 getter. Please consider this is for learning purpose. not for production level application:) just want to check how things can be done :) Please excuse me for my bad English.
If you simply want to refer to the inherited prop3 property, you could write return Object.getPrototypeOf(this).prop3;, but there is no point in doing this. It seems you don't want to overwrite the property so don't do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.