gpt4 book ai didi

javascript - 了解将函数作为 JavaScript 变量传递时变量会发生什么情况

转载 作者:行者123 更新时间:2023-12-03 08:28:25 25 4
gpt4 key购买 nike

好的。我正在尝试理解 JavaScript 中的闭包。我有一个函数,但我看到的结果不一致。传递 url 参数时没问题,除非它是在回调中完成的。我认为闭包会在函数中保留该值。

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

最佳答案

我怀疑您注释掉的部分中的某个地方:

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

关于javascript - 了解将函数作为 JavaScript 变量传递时变量会发生什么情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33443798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com