从关闭中返回?
如何从闭包返回而不从包含函数返回?
在以下函数中,return
语句实际上从 GM_xmlhttpRequest
返回:而不是闭包。当然,我可以看到我可以安排我的代码,以便执行在闭包结束时停止,但我很好奇如何在示例中提前返回。
function GM_xmlhttpRequest(details, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState != 4)
return; // <-- zomg returns from parent function wtf
if (xhr.status != 200)
callback(null);
callback(xhr);
}
xhr.open('GET', details.url, true);
xhr.send();
};
How does one return from a closure, without returning from the containing function?
In the following function, the return
statement actually returns from GM_xmlhttpRequest
: not the closure. Naturally I can see that I could arrange my code so that that execution drops off the end of the closure, but I'm curious as to how to early return in the example.
function GM_xmlhttpRequest(details, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState != 4)
return; // <-- zomg returns from parent function wtf
if (xhr.status != 200)
callback(null);
callback(xhr);
}
xhr.open('GET', details.url, true);
xhr.send();
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
return只会退出被调用者(当前函数)并将控制权返回给调用者(调用“父”函数),它永远不会从调用者返回。在您描述的情况下,被调用者是设置为onreadystatechange的匿名函数,并且没有调用者(本身)。
GM_xmlhttpRequest 在 onreadystatechange 函数运行之前的
xhr.send()
行之后返回 undefined,因为没有 >return 语句和 XHR 是异步的。 “zomg wtf”行将退出该匿名函数,因为没有调用者可以将控制权传递回。来自 ECMA-262 第 3 版和第 5 版(第 12.9 节 return 语句):
return will only ever exit the callee (current function) and return control to the caller (calling "parent" function), it will never the return from the caller. In the situation you describe, the callee is the anonymous function set to onreadystatechange and there is no caller (per se).
GM_xmlhttpRequest returns undefined after the
xhr.send()
line before the onreadystatechange function runs because there is no return statement and the XHR is asynchronous. The "zomg wtf" line will just exit that anonymous function since there is no caller to pass control back to.From ECMA-262, 3rd and 5th editions (section 12.9 The return statement):