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

我的代码是

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

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

LEY番长2020/03/12 16:48:05

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.

2020/03/12 16:48:05

And then there is this...

( document.exitPointerLock || Function )();
LEYPro前端2020/03/12 16:48:05

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
*/

小哥GOItachi2020/03/12 16:48:05
    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 16:48:05

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 16:48:05

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 16:48:05

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 16:48:05

I always check like this:

if(!myFunction){return false;}

just place it before any code that uses this function

米亚伽罗L2020/03/12 16:48:05

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 16:48:05

This simple jQuery code should do the trick:

if (jQuery.isFunction(functionName)) {
    functionName();
}
飞云Pro2020/03/12 16:48:05
function js_to_as( str ){
     if (me && me.onChange)
         me.onChange(str);
}
神乐小宇宙Gil2020/03/12 16:48:05

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

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

您甚至可以走得更远:

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

万一我也是异步的。

启人小次郎2020/03/12 16:48:04

尝试这样的事情:

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

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

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