如何检查 JavaScript 函数是否已定义?

front end technologyjavascriptweb development

在本教程中,我们将学习如何检查 JavaScript 函数是否已定义。如果程序员在未定义 JavaScript 函数的情况下调用该函数,他们将看到引用错误,并显示"函数未定义"之类的消息。

为了解决这个问题,程序员可以检查函数是否已定义并调用该函数。

我们将在下面介绍在 JavaScript 中检查函数是否已定义的各种方法。

使用 typeof 运算符

在 JavaScript 中,typeof 运算符可用于检查变量、函数、对象等的类型。当我们使用函数名称作为 typeof 变量的操作数时,它会返回 'function' 字符串,我们可以检查函数是否已定义。如果未定义函数,typeof 运算符将返回 'undefined'

语法

以下是 typeof 运算符的语法。

let isFunction = typeof function_name === 'function'

参数

  • function_name − 它是一个不带括号的函数名称,用户想要检查函数是否已定义。

示例

在下面的示例中,我们将创建名为 test() 的函数。我们将使用 typeof 运算符来检查 test() 函数是否已定义。如果函数已定义,我们将调用该函数。否则,我们将打印消息,如"函数未定义"。

<html> <head> </head> <body> <h2>Check if function is defined in Javascript.</h2> <h4>Check if function is defined using <i> typeof operator.</i></h4> <div id = "output"></div> <script> var output = document.getElementById("output"); function test() { output.innerHTML = "function test() is defined."; } if (typeof test === 'function') { test(); } else { output.innerHTML = "function is not defined."; } </script> </body> </html>

在上面的输出中,用户可以看到,当函数被定义时,控制权进入 if 语句,并打印函数中的消息。

使用 instanceof 运算符

在 JavaScript 中,instanceof 运算符用于检查对象类型变量的类型。函数、对象、数组等都是 JavaScript 对象类型。因此,程序员可以将其与 instanceof 运算符一起使用。

我们将使用 Function 对象作为 instanceof 运算符的右操作数,并使用函数名称作为左操作数。如果变量是函数类型,则返回 true,否则返回 false。

语法

用户可以使用以下语法,使用 instanceof 运算符检查函数是否已定义

let isFunction =function_name instanceof Function;

示例

以下 示例 演示了如何将 instanceof 运算符与函数对象结合使用。我们创建了 demo() 函数,并使用 instanceof 运算符检查了它是否已定义。

<html> <head> </head> <body> <h2>Check if function is defined in JavaScript.</h2> <h4>Check if function is defined using <i> instanceof operator.</i></h4> <div id = "output"></div> <script> var output = document.getElementById("output"); function demo() { output.innerHTML = "Inside the function call."; } if (demo instanceof Function) { demo(); } else { output.innerHTML = "function is not defined."; } </script> </body> </html>

使用 try-catch 块

在 JavaScript 中,try-catch 块可用于错误处理。当程序员调用未定义该函数时,JavaScript 会产生引用错误。我们将在 try 块中调用函数来处理错误。如果未定义该函数,则控制权会自动转到 catch 块来处理错误并终止程序的执行。

语法

用户可以按照以下语法使用 try-catch 块来检查函数是否已定义。

try {
   
   // call the function here
} catch (e) {
   
   // if the function is not defined, control comes here.
}

示例

以下示例演示了 try-catch 块 与函数调用的结合使用。我们定义了 demo() 函数并从 try 块中调用了 test() 函数。它将产生错误,并且控制权将进入 catch 块。

<html> <head> </head> <body> <h2>Check if function is defined in Javascript.</h2> <h4>Check if function is defined using <i> try-catch </i> block.</h4> <div id = "output"></div> <script> var output = document.getElementById("output"); function func() { output.inerHTML = "Inside the function call."; } try { test(); } catch (e) { output.innerHTML = "Inside the catch block. <br/>"; output.innerHTML += "function is not defined."; } </script> </body> </html>

在上面的输出中,用户可以看到 test() 函数未定义,因此控制权转到 catch 块并打印 catch() 块的所有消息。

我们已经了解了三种不同的方法来检查函数是否已定义。第一种方法和第二种方法非常相似,因为它们都检查对象类型。第三种方法不检查变量的类型,但如果在调用函数时发生任何错误,它会将控制权发送到 catch 块。


相关文章