简体   繁体   English

javascript对象继承如何工作?

[英]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. 我正在尝试学习javascript继承的工作方式。

Lets say an object named myObj is created as 假设一个名为myObj的对象被创建为

myObj = createSecObj();

Then value of myObj.prop3 is logged to the console as 然后,将myObj.prop3的值记录为控制台

console.log(myObj.prop3) // "prop1 prop2"

And then myObj.prop1 is changed as "blah" using 然后使用以下命令将myObj.prop1更改为“ blah”

myObj.prop1 = "blah"

And again if the myObj.prop3 is logged to the console it results "prop1 prop2". 再次,如果将myObj.prop3登录到控制台,则结果为“ prop1 prop2”。 and not "blah prop2". 而不是“ blah prop2”。

 console.log(myObj.prop3) // results "prop1 prop2", expecting "blah prop2"

Looks like obj.prop3 still refer its parent object. 看起来obj.prop3仍引用其父对象。 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. 看起来obj.prop3仍引用其父对象。 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 问题是您用以下方法覆盖了prop3

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 . obj.prop3将始终返回变量 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" . 该变量的值prop3不能在整个应用了改变,并在创建它的那一刻,它的值是"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. 如果您想获取"blah prop2"则只需从代码中删除上述行即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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