从关闭返回? [英] Return from closure?

查看:114
本文介绍了从关闭返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从闭包返回,而不从包含函数返回



在下面的函数中, return 语句实际上从返回GM_xmlhttpRequest :不是闭包。当然,我可以看到,我可以安排我的代码,以便执行结束的关闭,但我很好奇,如何早期返回的例子。

  function GM_xmlhttpRequest(details,callback){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState!= 4)
return; // < - zomg从父函数返回wtf
if(xhr.status!= 200)
callback(null);
callback(xhr);
}
xhr.open('GET',details.url,true);
xhr.send();
};


解决方案

退出 callee (当前函数)并将控制权返回给调用者(调用父函数),它将永远不会从 。在您描述的情况下,被调用者是设置为 onreadystatechange 的匿名函数,并且没有调用者(本身)。


$ b $在 onreadystatechange 之前的 xhr.send()行之后,

GM_xmlhttpRequest
em>函数运行,因为没有 return 语句,并且XHR是异步的。 zomg wtf行将退出该匿名函数,因为没有调用者将控制权返回。



第3版和第5版(第12.9节返回语句):


return语句导致函数停止执行并向
调用者返回一个值。如果省略 表达式,则返回值未定义。否则,返回值是 Expression 的值。



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

解决方案

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):

A return statement causes a function to cease execution and return a value to the caller. If Expression is omitted, the return value is undefined. Otherwise, the return value is the value of Expression.

这篇关于从关闭返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆