如何检查JavaScript函数是否已定义?
在本教程中,我们将学习如何检查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。
语法
用户可以使用以下语法来检查函数是否已定义:
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块。
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP