简体   繁体   中英

How javascript object inheritance work?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM