本文示範如何在 JavaScript 中判斷某個方法是否存在,避免呼叫不存在的函式時發生錯誤。
<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" 判斷型別,並搭配 try...catch 做額外防護,就能安全地呼叫可能不存在的方法。希望本文對你的 JavaScript 程式設計有所幫助。