我有以下对象:
var myObject = {
attributes: { name: "dev.pus", age: 29 },
someInjectedObject: {
name: "someComponent",
action: function() {
// do something
return this.this.attributes.name; // this surely won't work :(
}
}
};
如您所见,我希望从对象的嵌套部分获取myObject.attributes.name,而不必观察该值。
我该怎么做?如何定义参考?
修改 一个简单的myObject.attributes是不够的,因为myObject更改或更好地被分配给一个新变量。
答案 0 :(得分:4)
围绕对象创建一个闭包:
var myObject = (function() {
var result = {
attributes: { name: "dev.pus", age: 29 },
someInjectedObject: {
name: "someComponent",
action: function() {
// do something
return result.attributes.name;
}
};
};
return result;
})();
答案 1 :(得分:0)
你可以像这样直接引用myObject
:
var myObject = {
attributes: { name: "dev.pus", age: 29 },
someInjectedObject: {
name: "someComponent",
action: function() {
// do something
return myObject.attributes.name; // this surely will work :(
}
}
};
alert(myObject.someInjectedObject.action());