如何检查JavaScript中是否存在函数?

JavaScript

古一LEY

2020-03-12

我的代码是

function getID( swfID ){
     if(navigator.appName.indexOf("Microsoft") != -1){
          me = window[swfID];
     }else{
          me = document[swfID];
     }
}

function js_to_as( str ){
     me.onChange(str);
}

但是,有时我onChange无法加载。萤火虫错误

me.onChange不是一个函数

我想优雅地降级,因为这不是我程序中最重要的功能。typeof给出相同的错误。

关于如何确保它存在然后仅执行的任何建议onChange

(下面的任何一种方法都不能尝试抓到一件作品)

第1158篇《如何检查JavaScript中是否存在函数?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

13个回答
LEY番长 2020.03.12

This will verify if the function exists, if so it will be executed

me.onChange && me.onChange(str);

Thus the error TypeError: me.onChange is not a function is prevent.

null 2020.03.12

And then there is this...

( document.exitPointerLock || Function )();
LEYPro前端 2020.03.12

To illustrate the preceding answers, here a quick JSFiddle snippet :

function test () {
console.log()

}

console.log(typeof test) // >> "function"

// implicit test, in javascript if an entity exist it returns implcitly true unless the element value is false as :
// var test = false
if(test){ console.log(true)}
else{console.log(false)}

// test by the typeof method
if( typeof test === "function"){ console.log(true)}
else{console.log(false)}


// confirm that the test is effective : 
// - entity with false value
var test2 = false
if(test2){ console.log(true)}
else{console.log(false)}

// confirm that the test is effective :
// - typeof entity
if( typeof test ==="foo"){ console.log(true)}
else{console.log(false)}

/* Expected :
function
true 
true 
false
false
*/

小哥GOItachi 2020.03.12
    function sum(nb1,nb2){

       return nb1+nb2;
    }

    try{

      if(sum() != undefined){/*test if the function is defined before call it*/

        sum(3,5);               /*once the function is exist you can call it */

      }

    }catch(e){

      console.log("function not defined");/*the function is not defined or does not exists*/
    }
小宇宙神无 2020.03.12

I have also been looking for an elegant solution to this problem. After much reflection, I found this approach best.

const func = me.onChange || (str => {}); func(str);

神奇西里 2020.03.12

Put double exclamation mark i.e !! before the function name that you want to check. If it exists, it will return true.

function abc(){
}
!!window.abc; // return true
!!window.abcd; // return false
米亚小小神乐 2020.03.12

With no conditions

me.onChange=function(){};

function getID( swfID ){
     if(navigator.appName.indexOf("Microsoft") != -1){
          me = window[swfID];
     }else{
          me = document[swfID];
     }
}

function js_to_as( str ){
     me.onChange(str);
}
Gil伽罗 2020.03.12

I always check like this:

if(!myFunction){return false;}

just place it before any code that uses this function

米亚伽罗L 2020.03.12

In a few words: catch the exception.

I am really surprised nobody answered or commented about Exception Catch on this post yet.

Detail: Here goes an example where I try to match a function which is prefixed by mask_ and suffixed by the form field "name". When JavaScript does not find the function, it should throw an ReferenceError which you can handle as you wish on the catch section.

function inputMask(input) {
  try {
    let maskedInput = eval("mask_"+input.name);

    if(typeof maskedInput === "undefined")
        return input.value;
    else
        return eval("mask_"+input.name)(input);

  } catch(e) {
    if (e instanceof ReferenceError) {
      return input.value;
    }
  }
}

Gil伽罗 2020.03.12

This simple jQuery code should do the trick:

if (jQuery.isFunction(functionName)) {
    functionName();
}
飞云Pro 2020.03.12
function js_to_as( str ){
     if (me && me.onChange)
         me.onChange(str);
}
神乐小宇宙Gil 2020.03.12

没看到这个建议:me.onChange && me.onChange(str);

基本上,如果me.onChange是未定义的(如果尚未启动,它将是未定义的),则它将不执行后一部分。如果me.onChange是一个函数,它将执行me.onChange(str)。

您甚至可以走得更远:

me && me.onChange && me.onChange(str);

万一我也是异步的。

启人小次郎 2020.03.12

尝试这样的事情:

if (typeof me.onChange !== "undefined") { 
    // safe to use the function
}

或更好(根据UpTheCreek推荐的评论)

if (typeof me.onChange === "function") { 
    // safe to use the function
}

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android