我有一个包装函数,我在其中使用变量dataObject。我有一个动作来触发包装函数中的一些外部函数。
function wrapper() {
var dataObject;
var jsonPath = "dataObject[0]['Set1'][0]['Attribute1']";
eval('outsideFunction(dataObject, jsonPath)');
}
function outsideFunction(dataObject, jsonPath) {
dataObject[0]['Set1'][0]['Attribute1'] = 'asde'; //This sets the value to dataObject in the wapper
var attrVal = '123';
eval("jsonPath = attrVal"); //This doesn't set value to dataObject in the wrapper but in the local dataObject
}
为什么使用eval直接分配和分配的操作有区别?
答案 0 :(得分:1)
根据您data[0]['Set1'][0]['Attribute1']
的结构,可以写成data[0].Set1[0].Attribute1
,这里是代码,但我认为您不太了解您要求的套数。
var wrapper, outsideFunction;
wrapper = function(){
someOb = {};
var data = [
{
Set1: [
{
Attribute1: null, // we will change null to 'asdf' below
},
],
},
];
outsideFunction(data, someOb);
console.log( someOb.newProp, someOb.dumb );
// outputs 'hehehehe', undefined
};
outsideFunction = function(data, blah) {
data[0].Set1[0].Attribute1 = 'asdf';
//blah is a reference to someOb
// we can change a part of blah and it will look at the reference and change someOb
blah.newProp = 'hehehehe';
// but if we do `blah =`, then we reference a new object
// This won't affect someOb, blah will just be a different object talking about something else
blah = { dumb: false };
};
所以,就像我说的那样,你的数据对象是一个编号集(你有[0]
),然后是一个命名集(Set1
),然后是一个编号集([0]
),我认为你的意思不是那么多。
numberedSet = [
{
name: 'dan',
likes: [
'coding', 'girls', 'food',
],
},
{
name: 'Sreekesh',
},
]
namedSet = {
dan: {
isPerson: true,
likes: [
'coding', 'girls', 'food',
],
},
Sreekesh: {
isPerson: true,
askedQuestion: function(){
return true;
},
}
};
numberedSet[0].name == dan; // true
numberedSet[0].likes[1] == 'girls'; // true
namedSet.dan.isPerson == true; // true
namedSet.Sreekesh.askedQuestion(); // true