我正在尝试使用另一个值(数组)作为参数将对象值设置为函数调用,但是,由于某种原因,该值返回为未定义,我接着尝试访问该值。它在IIFE中。
我不确定为什么会发生这种情况,因为据我所知,范围界定是可以的,价值应该在那时初始化并执行?
这是一个简化的例子:
(function(){
var minefield = [1,2,3,'M',4,5,6];
function findMachine(minefieldMachine) {
return minefieldMachine === 'M';
}
var terrain = {
start:{initialMachienLocation:minefield.findIndex(findMachine)},
currentMutable:{mutableIndex:terrain.start.initialMachineLocation}//Error: "Uncaught type error cannot read property 'start' of undefined"
//Why isn't the above accessing the value declared in terrain.start.initialMachineLocation through the function call?
}
}());
然而,这样做是有效的,从上面脱离上下文:
function findMachine(minefield){return minefield === 'M'}
[1,2,3,'M',4,5,6].findIndex(findMachine);
//above returns the proper index value, 3.
答案 0 :(得分:3)
这与该功能无关。
你要做的是,基本上,这是:
var foo = {
a: 1,
b: foo.a
}
您需要考虑操作的顺序。
对象文字构造一个然后分配给变量foo
的对象。
...除了在构造对象时,您正在尝试读取foo
的值。它还没有,所以失败了。
您需要分两步完成此操作。
var foo = {
a: 1,
}
foo.b = foo.a;