2015-07-19 48 views
3

一些变量可以在Javascript执行过程中“优化”出来。因此,这些变量的值在调试时不可用于检查(User documentation)。变量视图显示(优化掉)消息和控制台抛出如果变量试图要评估以下错误:如何获取已优化的变量值?

Error: variable has been optimized out 

是否有任何方式来实施这种可变的评价或禁用在Firefox这个优化?

+4

你能否提供可触发此优化的示例JS代码? – simbabque

+0

http://stackoverflow.com/help/mcve –

+0

向我们展示导致此问题的实际代码。 – jfriend00

回答

3

以阻止此优化的方式使用该变量。

function NOP() {} 

// then in the optimised code 

    NOP(myvar); 
    // debugging here should now show `myvar` 
1

当一个变量被“优化掉”时,它只是表示它没有在当前范围的上下文中被修改。因此,JavaScript引擎已经做了一些优化魔术,并暂时隐藏了该变量。例如,假设你正在使用lodash遍历某种类型的集合。

var parentThingy = []; 
var childThingy = []; 
_.each (collectionThingy, function(data){ 

    // parentThingy is not being modified inside this callback 
    // so it will be "optimized away" while you are inside this 
    // function scope. 

    var transformed; 
    if (data.someFlag) { 
     transformed = transformDataSomehow(data); 
    } 

    // childThingy is being modified, so you will be able to 
    // see its value in the debugger. 

    if (transformed) { 
     childThingy.push(transformed); 
    } 
}); 

// Now that you've exited the callback scope, you will be able to see 
// the value of parentThingy again. 

if (childThingy.length > 1){ 
    parentThingy.push(childThingy); 
} 

您可以使用NOP建议强制parentThingy是在回调范围可见,但因为你不修改parentThingy该回调里面,你不需要看到它。它没有改变,也不会改变。这与您当前正在调试的代码无关。一旦你退出了回调的范围,parentThingy将再次被调试器看到。

仅供参考:这不是Firefox的事情。 Chrome做同样的事情,它只是使用不同的措词来表明该变量与当前范围无关。

+0

我强烈反对声明“你不需要看到它”。如果您正在开发代码,而且您正在尝试调试不同的值以尝试调试某些内容,则完全有可能需要查看它。除了通过hacky NOP()技巧之外,没有选择可以看到它,令人沮丧 – Stewart