如何从javaScript中的子对象的acess父对象属性

问题描述 投票:0回答:3

如何从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
3个回答
3
投票

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()

对于您的参考:

propertyconscontors

和dodestructurativer更详细地。 prototypes:object.create()

object.getPrototypeof() 请注意,如果您这样做: let m = {x:1,y:2}; let n = Object.create(m); 然后nm是对象。这意味着您可以使用上述示例访问其属性。


访问原型对象的属性:

Object.getPrototypeOf()


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


1
投票

    

我今天正在寻找解决这个问题的解决方案。对于我的用例,这就是我解决的方式。

var parentObject = { title: "My object", nestedArrayOfMoreObjects: [ {nestedObj1: "this is object 1", getParentObj: function() { this.parentObj = parentObject; } }, {nestedObj2: "this is object 2", getParentObj: function() { this.parentObj = parentObject; } }, {nestedObj3: "this is object 3", getParentObj: function() { this.parentObj = parentObject; } }] }

这对我有用,因为我想根据某些条件创建一个从每个“父对象”中创建一些数组项的新数组(在我的代码中,有几个不同的父对象,具有不同的名称和属性! )。 然后,我希望能够将我的新数组中的所有物品链接到他们的尊敬的父母,以及这些父母的其他特性。
因此,我创建了一个函数来对我的新数组中的每个对象执行AddParents()方法(控制台日志只是为了检查其工作。
function addParents() {
            newArray.forEach(
                (item) => {
                    item.getParentObj();
                    console.log(item.parentObj);
                    console.log(item.parentObj.title);
                }
            )
        }

        addParents(); 
一旦该功能运行,我就可以使用我的新数组中项目上的任何父对象属性:

newArray[0].parentObj.title


0
投票
这有点令人费解,但这是我发现可以访问父对象及其属性的解决方案!

	

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.