頁面引入多個 JS 文件,順序不確定,需在 window.onload 中安全調用可能存在的函數,避免 ReferenceError 或 TypeError。
window.onload = function() {
// 1. typeof 檢查類型為 'function' (避免同名變量非函數)
// 2. 直接引用標識符 (若不存在會拋 ReferenceError,需配合 typeof)
if (typeof test === 'function') {
test(); // 安全調用
}
};
typeof?// ❌ 直接判斷:若 test 未聲明 → ReferenceError
if (test && typeof test === 'function') { ... }
// ✅ typeof 未聲明標識符返回 'undefined',不拋錯
if (typeof test === 'function') { ... }
typeof 是唯一對未聲明標識符不拋錯的操作符。
<script>
window.onload = function() {
try {
// 檢查全域函數 test 是否存在且為函數
if (typeof test === 'function') {
test();
} else {
console.log('函數 test 不存在或非函數');
}
} catch (e) {
console.error('調用異常:', e);
}
};
function test() {
alert('我是 test() 方法');
}
</script>
// 檢查 MyApp.utils.format
if (typeof MyApp !== 'undefined' &&
typeof MyApp.utils !== 'undefined' &&
typeof MyApp.utils.format === 'function') {
MyApp.utils.format(...);
}
// 通用安全獲取函數
function getFunction(path) {
var parts = path.split('.');
var obj = window;
for (var i = 0; i < parts.length; i++) {
if (obj == null) return null;
obj = obj[parts[i]];
}
return typeof obj === 'function' ? obj : null;
}
var fn = getFunction('MyApp.utils.format');
if (fn) fn();
import/export) 靜態依賴,編譯期即可發現缺失。import('./module').then(m => m.default()) 替代全域檢測。window.MY_APP),減少衝突。typeof fn === 'function' 是判斷函數存在性的標準安全寫法。window.onload 確保 DOM 與腳本就緒。typeof 短路特性。