2015-10-30 52 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

相关问题