How get value of variable that has been optimized out?

主宰稳场 提交于 2019-12-01 03:58:52

问题


Some variables can be "optimized out" during Javascript execution. Thus values of such variables are not available for inspection while debugging (User documentation). Variables view shows (optimized away) message and console throws following error if the variable is tried to be evaluated:

Error: variable has been optimized out

Is there any way to enforce evaluation of such variable or disable this optimization in Firefox?


回答1:


Use the variable in a way that prevents this optimisation.

function NOP() {}

// then in the optimised code

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



回答2:


When a variable has been "optimized away," it just means that it's not being modified in the context of the current scope. Hence, the JavaScript engine has done some optimization magic and stashed that variable out of the way for the time being. For example, say you're using lodash to iterate over a collection of some kind.

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);
}

You could use the NOP suggestion to force parentThingy to be visible in the callback scope, but since you're not modifying parentThingy inside that callback, you don't need to see it. It hasn't changed and won't change. It's not relevant to the code you're currently debugging. Once you've exited the callback's scope parentThingy will be visible to the debugger again.

FYI: this isn't a Firefox thing. Chrome does the same thing, it just uses different verbiage to indicate the variable is irrelevant to the current scope.




回答3:


If you need to debug this variable, then you have to set the breakpoint at a place inside the function where this variable is declared.

Lets say you need to debugg the variable

"value"

function(value) {
   // If you set the breakpoint somewhere here it is OK

   myArray.map(function() {

       // If you set the breakpoint here you will get a Error: variable has been optimized out

   }

} 


来源:https://stackoverflow.com/questions/31503178/how-get-value-of-variable-that-has-been-optimized-out

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!