将参数传递到匿名onreadystatechange回调的普通纯JavaScript(即非JQuery)方法是什么?
例如:
function doRequest(){ /* Get an XMLHttpRequest in a platform independent way */ var xhttp = getXmlHttpRequestObject(); var msg="show this message when done"; /* another variable to pass into callback */ /* How do I pass 'msg' and 'xhttp' into this anonymous function as locals named 'x' and 'm'??? */ xhttp.onreadychangestate=function(x,m) { if( x.readyState == 4 ) { alert(m); } } /* do the open() and send() calls here.... */ }
Javascript支持闭包,因此您编写的匿名函数将能够从封闭范围访问xhttp和访问。msg``doRequest()
xhttp
msg``doRequest()
如果要显式地执行此操作(例如,如果要在代码中的其他位置定义回调函数并重用它),则可以创建一个函数来创建回调。这也使您可以使用不同的名称(例如x和m)来对变量进行别名别名:
x
m
function createCallback(x, m) { return function() { /* Do whatever */ }; }
然后doRequest(),做xhttp.onreadystatechange = createCallback(xhttp, msg);
doRequest()
xhttp.onreadystatechange = createCallback(xhttp, msg);
如果您只想“重命名”变量,则可以内联和匿名进行:
xhttp.onreadystatechange = (function(x, m) { return function() { /* Do stuff */ } })(xhttp, msg);