如何从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
。
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);
然后n
和m
是对象。这意味着您可以使用上述示例访问其属性。
访问原型对象的属性:
Object.getPrototypeOf()
function testingSetValuetoInheritedProperty() {
let m = {x:1,y:2};
let n = Object.create(m);
console.log(Object.getPrototypeOf(n).x)
}
testingSetValuetoInheritedProperty()
我今天正在寻找解决这个问题的解决方案。对于我的用例,这就是我解决的方式。
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;
}
}]
}
function addParents() {
newArray.forEach(
(item) => {
item.getParentObj();
console.log(item.parentObj);
console.log(item.parentObj.title);
}
)
}
addParents();
newArray[0].parentObj.title