「setTimeout 傳參數」是個經典疑問,網路上流傳的寫法多半繞來繞去,甚至要你重寫整個函式。本文示範一個實作中真的會遇到的案例,並說明為什麼某些寫法行得通、某些行不通。
有一個表單,需要在點擊送出時延遲執行 Ajax。最直覺的寫法是這樣:
<input type="submit" name="subt" value="send"
onclick="doAjax(sform.txtara.value); return false;" />
而 JS 裡可以寫成:
setTimeout("doAjax(document.sform.txtara.value)", 1000);
這種把「呼叫語法當字串」傳進去的寫法,在傳遞表單欄位值時是可行的,因為字串會被延遲到執行時才求值。但一旦要傳遞其他參數,尤其是物件,就會踢到鐵板。
如果你改寫成 setTimeout("doAjax(obj)", 1000),obj 這個字串會在全域作用域中被求值,而區域變數或 this 所指的物件在那個時空裡並不存在,於是就拿到 undefined 或拋錯。
關鍵是:不要用字串,用函式。把要傳的東西用閉包夾住:
function doAjax(msg, obj) {
alert(obj.value);
var he = "he=" + msg;
var ajaxrequest = initAjax();
ajaxrequest.open("POST", "abc.jsp", true);
ajaxrequest.setRequestHeader(
"Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
ajaxrequest.send(he);
ajaxrequest.onreadystatechange = function () {
if (ajaxrequest.readyState == 4) {
if (ajaxrequest.status == 200) {
document.getElementById("showpane").innerHTML =
ajaxrequest.responseText;
} else {
doAjax(msg, obj);
}
}
};
}
// 傳物件:用閉包直接夾住
setTimeout(function () {
doAjax(document.sform.txtara.value, document.forms['sform'].elements['subt']);
}, 1000);
另一種更乾淨的做法是把 this 先存起來:
var self = this;
setTimeout(function () { doAjax(msg, self); }, 1000);
標準的 setTimeout 本身就支援從第三個參數開始逐一傳入,這是 ES5 之後的行為:
setTimeout(doAjax, 1000, msg, obj);
或者用 bind 事先綁好:
setTimeout(doAjax.bind(null, msg, obj), 1000);
箭頭函式也可以,而且能直接沿用外層的 this:
setTimeout(() => doAjax(msg, this), 1000);
function initAjax() {
var httprequest = null;
try {
httprequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
httprequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
try {
httprequest = new XMLHttpRequest();
} catch (e) {
httprequest = null;
}
}
}
return httprequest;
}
今天只需 new XMLHttpRequest() 或 fetch() 即可,上面這段三層 try/catch 屬於歷史遺跡。
結論其實只有一句:setTimeout 的第一個參數永遠該是函式,而不是字串。字串寫法等同 eval,除了無法正確傳遞物件,還會帶來安全性與除錯上的困擾。改用閉包、bind 或直接傳參數,問題自然消失。