如果我有以下代码:
func({
item: {
subItem: 89
},
item2: {
message: 'I want the item.subItem value to be inside this value as well'
}
});
是否可以将item.subItem
值传递到item2.message
,而不在func()
内进行任何替换?
答案 0 :(得分:5)
除非您从对象定义之外指定它,否则这是不可能的:
var obj = {
item: {
subItem: 89
},
item2: {}
};
obj.item2.message = 'I want the ' + obj.item.subItem + ' value to be inside this value as well';
func(obj);
答案 1 :(得分:1)
没有。它们是独立的对象。如果你认为你需要这个,那么让对象有一个类允许它做一些有用的事情(例如,模板化)。
答案 2 :(得分:0)
这样的东西?
var anItem = { subItem: 89 };
func({
item: anItem
},
item2: {
message: anItem
}
});
答案 3 :(得分:0)
不是直接的..我会这样做:
function func(a)
{
alert(a);
}
func
(
new Item(10)
);
function Item(subItemVal)
{
this.item = { subItem: subItemVal };
this.item2 = { message: 'I want the ' + subItemVal + ' value to be inside this value as well' };
}
答案 4 :(得分:0)
不,但您可以执行以下操作,自动将所有item.XXX
子字符串替换为项目列表中的相应条目:
function func(data) {
for (var key in data.item)
data.item2.message = data.item2.message.replace('item.'+key, o.item[key])
print(data.item2.message) // I want the 89 value to be inside this value as well
答案 5 :(得分:0)
我不确定你为什么要这样做,但你可以做这样的事情。
这非常黑客,我真的不推荐它,但我认为它符合你的要求......?
注意:已提供更好的解决方案。
<强> Live example 强>
func(test = {
item: {
subItem: 89
},
item2: {
message: 'I want the item.subItem value to be inside this value as well'
}
},test.item2.message += ' ' + test.item.subItem );
function func ( obj ) {
alert( obj.item2.message );
}