呼叫一個不確定的函式(例如第三方外掛的選用功能、使用者設定的回呼)時,若直接呼叫而函式不存在,就會丟出 TypeError 中斷整個流程。事前判斷因此成為必要的防禦手段。
<html>
<head>
<title>js 判斷某個方法是否存在</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<script type="text/javascript">
window.onload = function () {
try {
if (test && typeof (test) == "function") {
test();
}
} catch (e) {
alert("方法不存在");
}
};
function test() {
alert("我是 test() 方法");
}
</script>
</head>
<body></body>
</html>
這裡的 typeof(test) == "function" 是核心判斷。加上 test && 前置檢查,是為了避免 test 完全未宣告時的 ReferenceError(在嚴格模式下尤其重要)。而外層的 try/catch 則是多一層保險,攔住函式執行過程中拋出的其他錯誤。
多數情況下不需要 try/catch,一行就夠:
if (typeof test === 'function') {
test();
}
typeof 對未宣告的識別字不會丟錯,會直接回傳字串 'undefined',這正是它比 test !== undefined 更安全的原因。
如果是檢查某個物件是否具備某方法(典型的 duck typing):
if (obj && typeof obj.method === 'function') {
obj.method();
}
這裡的 obj && 是必要的——若 obj 是 null 或 undefined,存取 obj.method 本身就會丟錯。可選鏈運算子提供了更簡潔的等價寫法:
obj?.method?.();
typeof,最簡潔。try/catch。
if (typeof window.requestAnimationFrame !== 'function') {
window.requestAnimationFrame = function (cb) {
return setTimeout(cb, 16);
};
}
這是最實用的一種形態:判斷不只是為了避免報錯,而是為了在具備能力時走最佳路徑、不具備時走相容路徑。