typeof方法
要检查是否已定义特定函数名称,我们可以使用 typeof 运算符:
if (typeof myFunctionName === 'function') {
myFunctionName();
}
在给定的情况下, typeof 运算符将返回 undefined 因为 myFunctionName() 尚未定义。
因此,不会执行 IF 语句中的函数调用。
如果函数存在,typeof 运算符将返回字符串“function”:
function test() {
console.log('Welcome to onitroad');
}
//Call the function above if it exists.
if (typeof test === "function") {
test();
}
typeof运算符
typeof 运算符获取未计算的操作数的数据类型,它可以是文字或者数据结构,如对象、函数或者变量。
typeof 返回一个带有变量类型名称的字符串作为第一个参数(对象、布尔值、未定义等)。
在 ECMAScript 2014 之前, typeof 总是为它提供的任何操作数返回一个字符串。
它永远不会产生错误。
但是在声明之前,在块中的 let 和 const 变量上使用 typeof 添加 let 和 Statements/const 后,将生成 ReferenceError。
try...catch 方法
还有一种 try...catch 语句的方法可以捕获函数 ReferenceError 错误。
这种方法将函数调用包装在语句的 try 块中,如下所示:
try {
eval('a x b');
} catch (err) {
console.log(err.name); //"SyntaxError"
console.log(err.message); //"Unexpected identifier"
}
如果该函数不存在,则会发生错误。
有时我们会在调用尚未定义的函数时遇到错误。
其中我们建议两种方法来检查函数是否存在。
日期:2020-06-02 22:16:10 来源:oir作者:oir
