javascript - Return from closure? -
how 1 return closure, without returning containing function?
in following function, return
statement returns gm_xmlhttprequest
: not closure. naturally can see arrange code that execution drops off end of closure, i'm curious how return in example.
function gm_xmlhttprequest(details, callback) { var xhr = new xmlhttprequest(); xhr.onreadystatechange = function() { if (xhr.readystate != 4) return; // <-- zomg returns parent function wtf if (xhr.status != 200) callback(null); callback(xhr); } xhr.open('get', details.url, true); xhr.send(); };
return ever exit callee (current function) , return control caller (calling "parent" function), never return caller. in situation describe, callee anonymous function set onreadystatechange , there no caller (per se).
gm_xmlhttprequest returns undefined after xhr.send()
line before onreadystatechange function runs because there no return statement , xhr asynchronous. "zomg wtf" line exit anonymous function since there no caller pass control to.
from ecma-262, 3rd , 5th editions (section 12.9 return statement):
a return statement causes function cease execution , return value caller. if expression omitted, return value undefined. otherwise, return value value of expression.
Comments
Post a Comment