2015-10-30 49 views
0

好的。我想了解JavaScript中的閉包。 我有一個功能,但我看到不一致的結果。當傳遞url參數時,除非在回調中完成,否則沒關係。我認爲閉幕會保留這個功能的價值。瞭解將變量作爲JavaScript變量傳遞時變量會發生什麼變化

ABC.print = function (reportId, format, reportTitle) { 
     alert("Coming in=" + format); // Always has right value. 

     var url = 'Main/MyModule/Print?reportId=' + reportId; 
     url += '&format=' + format; 
     url += '&reportTitle=' + reportTitle; 

     function printWindow(urlString) { 
      window.open(urlString, 'Print', "toolbar=no,menubar=no,status=no"); 
     };  

     // What is the difference between? 
    if (someCondition) 
    { 
     // Variables in url are not current, they retain first time value only. 
     SomeFunction("Text", "Text 2", function() { printWindow(url); }); 
    } 
    else { 
     // Variables are always current 
     printWindow(); 
    } 
}; 
+0

[你,而這個檢查(https://www.google.com.bd/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=javascript%20scope)。 –

回答

1

我懷疑的地方在你的註釋部分:

// Actually some logic but to simplify... 

的價值你的變量url改變。

當函數printWindow()被調用時,它會在那個時候電話就被打出(而不是url在定義函數時的值。

的的話題url值範圍可能會搞砸:你的var url=...只存在於函數ABC.print內,只要程序執行在ABC.print之內,var就會有可預測的結果,但只要你將函數printWindow()作爲回調傳遞到別的地方,不再在ABC.print範圍內,因此url值未定義,或最多不穩定/不可預測。

爲了解決這個問題,你可以給變量url全局作用域:定義它在任何函數之外的某個地方,以便它在任何地方都可用。

// global scope 
var url; 

ABC.print = function (reportId, format, reportTitle) { 
    alert("Coming in=" + format); 

    // give the global variable content here 
    url = 'Main/MediaReach/Print?reportId=' + reportId; 
    url += '&format=' + format; 
    url += '&reportTitle=' + reportTitle; 

    printWindow = function() { 
    alert("ulr = " + url); 
    window.open(url, 'Print', "toolbar=no,menubar=no,status=no"); 
    }; 

    // Actually some logic but to simplify... 
    printWindow(); 

    // passing printWindow as callback 
    doSomething('myParam',printWindow); 
}; 
+0

實際上,邏輯檢查計數並調用printWindow()或使用printWindow()作爲回調調用JqueryUI對話框。我沒有在其他地方操縱網址。 – PrivateJoker

+0

我聽到你在說什麼,但我仍然試圖理解你在說什麼。如果我擺脫PrintWindow,只是通過window.open(...),那麼它有正確的網址。然而,它隨後與我的回調攪亂。 – PrivateJoker

+0

是的,使全球網址值做到了。然而,我不確定爲什麼我必須使它成爲全局的,因爲正確的價值被傳遞到主函數中。 – PrivateJoker

相關問題