But I wonder: How does it keep the local stack frame alive to access the local variable when the function returns immediately? Is the nested function translated into a closure that will keep a reference to the XHR variable (which would then not live on the stack at all)?
The JavaScript engine is dealing with all the life cycle management of the variables, but yes, they're essentially closures. Anonymous functions are supported by
pas2js as well, so you can write this, too:
procedure PostData(aData: String);
var
xhr: TJSXMLHttpRequest;
begin
xhr := TJSXMLHttpRequest.new;
xhr.addEventListener('load', procedure(aEvent: TEventListenerEvent)
begin
if xhr.Status = 200 then
Writeln('Ok')
else
Writeln('Error: ', xhr.Status);
end);
xhr.open('POST', '/myapp/myapi');
xhr.send(aData);
end;
What other things are allowed here that would normally not work at all, like for example returning pointers to local variables, etc.? Are these things (and their limits) clearly defined as new features or do they just happen under certain circumstances (like here) as a side effect and nobody is talking about it?
You can't have pointers in JavaScript and thus
pas2js (at least not in the way you're thinking). Passing on references to classes, etc. is safe however, cause again, their life cycle is managed by the JS engine.