JavaScript 如何检查函数是否被定义

JavaScript 如何检查函数是否被定义

在本文中,我们的任务是识别一个函数是否被定义。JavaScript的typeof运算符用于解决下面描述的问题:

Javascript typeof运算符 这个运算符可以用来找到JavaScript变量的类型。它返回一个变量或表达式的类型:

语法:

typeof var
JavaScript

参数: 它包含一个单一值 var ,它是一个Javascript变量。

返回值: 它返回一个变量或表达式的类型:

示例1: 这个示例检查函数的类型,如果它是一个函数,则使用 typeof 运算符 定义,否则未定义。

<body style="text-align:center;"> 
  
    <h1 style="color:green;"> 
        GeeksForGeeks 
    </h1> 
    <h3>How to check a function is defined</h3> 
  
    <p id="GFG_UP" style="font-size: 16px;  
                          font-weight: bold;"> 
    </p> 
  
    <button onclick="gfg_Run()"> 
        Click here 
    </button> 
  
    <p id="GFG_DOWN" style="color:green;  
                            font-size: 20px;  
                            font-weight: bold;"> 
    </p> 
  
    <script> 
        var el_up = document.getElementById("GFG_UP"); 
        var el_down = document.getElementById("GFG_DOWN"); 
          
        el_up.innerHTML = 
            "Function named 'fun' which is not defined"; 
              
        function gfg_Run() { 
            var defined = 'Not defined'; 
            if(typeof fun == 'function') { 
                defined = "Defined"; 
            } 
            el_down.innerHTML = defined; 
        }         
    </script> 
</body>
HTML

输出:

JavaScript 如何检查函数是否被定义

示例2: 此示例检查函数的类型,如果它是一个函数,则通过使用 typeof运算符 创建一个函数对其进行定义,否则未定义。

<body style="text-align:center;"> 
  
    <h1 style="color:green;"> 
        GeeksForGeeks 
    </h1> 
    <h3>How to check a function is defined</h3> 
  
    <p id="GFG_UP" style="font-size: 16px;  
                          font-weight: bold;"> 
    </p> 
  
    <button onclick="gfg_Run()"> 
        Click here 
    </button> 
  
    <p id="GFG_DOWN" style="color:green;  
                            font-size: 20px;  
                            font-weight: bold;"> 
    </p> 
  
    <script> 
        var el_up = document.getElementById("GFG_UP"); 
        var el_down = document.getElementById("GFG_DOWN"); 
          
        el_up.innerHTML = "Function named 'fun' which is defined"; 
          
        function isFunction(possibleFunction) { 
            return typeof(possibleFunction) === typeof(Function); 
        } 
          
        function fun() { 
              
        } 
          
        function gfg_Run() { 
            var defined = 'Not defined'; 
            if(isFunction(fun)) { 
                defined = "Defined"; 
            } 
            el_down.innerHTML = defined; 
        }         
    </script> 
</body>
HTML

输出:

JavaScript 如何检查函数是否被定义

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册