【问题标题】:How to acess parent object properties from child object in JavaScript如何在 JavaScript 中从子对象访问父对象属性
【发布时间】:2020-10-10 08:20:54
【问题描述】:

如何在 JavaScript 中从子对象访问父对象属性。

function testingSetValuetoInheritedProperty() {
    
   let m = {x:1,y:2};
    
   let n = Object.create(m);
    
   **console.log(n.prototype.x);**
    
   return n
    
}

我收到TypeError: Cannot read property 'x' of undefined

【问题讨论】:

    标签: javascript object prototype


    【解决方案1】:

    有多种方法可以访问对象的属性。

    function testingSetValuetoInheritedProperty() {
    
       let m = {x:1,y:2};
       let n = Object.create(m); // m becomes a prototype of object n
    
       //first - dot property accessor
       console.log(n.x);
       //second - square brackets property accessor
       console.log(n['x']);
       //third - object destructuring
       const { x } = n;
       console.log(x)
       
       
       console.log('-------Prototype------')
    
       //working with prototype of n
    
       //first
       console.log(Object.getPrototypeOf(n).x)
       //second
       console.log(n.__proto__.x) // <--- no longer recommended
    
    }
    
    testingSetValuetoInheritedProperty()

    供您参考property accessorsdestructuring 更详细。

    原型: Object.create()Object.getPrototypeOf()Object.prototype.proto


    请注意,如果您这样做:

       let m = {x:1,y:2};
    
       let n = Object.create(m);
    

    那么nm 都是对象。这意味着您可以使用上面的示例来访问它们的属性。

    【讨论】:

    • 但是,我的问题是如何从孩子访问父道具
    • 对不起,我稍微误解了这个问题。我编辑了答案以说明使用原型的原因,但您似乎已经弄清楚了。干得好。
    【解决方案2】:

    要访问原型对象的属性,请使用:Object.getPrototypeOf()

    function testingSetValuetoInheritedProperty() {
         
       let m = {x:1,y:2};
       let n = Object.create(m);
         
       console.log(Object.getPrototypeOf(n).x)
    }
    testingSetValuetoInheritedProperty()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-26
      • 2019-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多