2015-07-19 34 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