假设我有一个对象
var BOB = {
"name": "bob",
"height": 185
};我有另一个对象,它引用它的值。
var PROPS = {
"bob": {
"height": BOB.height
};因此,现在PROPS.bob.height将等于185。如果我把物体串起来,我就会得到
{"bob": {"height": 185}}我能否计算出返回值185的值的字符串值。例如从代码中计算出源代码.:
var s = findOutTheSourceCode(PROPS);
// s would be
/*
{
"bob": {
"height": BOB.height
}
*/发布于 2016-10-10 11:49:03
一般情况下,不。不管怎么说,这些信息都不会被储存。
如果代码是函数和的一部分,您将引用该函数和,您使用的JS引擎支持这一非标准特性,那么您可以调用thatfunction.toString(),然后尝试使用(例如)模式匹配找到相关的代码位。
发布于 2016-10-10 12:02:23
从设计的角度来看,这是一个非常糟糕的想法。
总之,在回答你的问题时,简短的回答是“不,你不能”。
但是,有一个丑陋的回答说是的,代价是依赖使用eval -这是一个更糟糕的想法。示例:
var BOB = {
"name": "bob",
"height": 185
};
var PROPS_src = '{\n'
+ ' "bob": {\n'
+ ' "height": BOB.height\n'
+ ' }'
+ '}';
eval('var PROPS = '+PROPS_src);
console.log("PROPS_SRC:__________________");
console.log(PROPS_src);
console.log("PROPS:______________________");
console.log(PROPS);
// Output:
// PROPS_SRC:__________________
// {
// "bob": {
// "height": BOB.height
// }}
// PROPS:______________________
// { bob: { height: 185 } }但是,正如我所说的,所有这些都是的坏主意,。我不建议您重新设计您的数据结构(如果需要的话,还可以使用一种跟踪数据来源的方式)。
例如(快速和肮脏):
var people = {
bob: {
"name": "bob",
"height": 185
}
};
var props = {
"bob": {
"someConstant": "Hello World",
"_height": "height",
}
};
function getProps(who){
var out = {};
Object.keys(props[who]).map(function(k){
if (k.substring(0,1) == "_") {
out[k.substring(1)] = people[who][props[who][k]];
} else {
out[k] = props[who][k];
};
});
return out;
};
console.log("Raw:", props['bob']);
console.log("Calculated:", getProps('bob'));
// Output:
// Raw: { someConstant: 'Hello World', _height: 'height' }
// Calculated: { someConstant: 'Hello World', height: 185 }https://stackoverflow.com/questions/39957556
复制相似问题