我的代码是

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不加载。Firebug错误

我。onChange不是一个函数

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

关于如何确保它存在,然后只执行onChange有什么建议吗?

(下面的方法除了try catch one work之外都没有)


当前回答

我也一直在寻找这个问题的优雅解决方案。经过深思熟虑,我发现这种方法是最好的。

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

其他回答

我总是这样检查:

if(!myFunction){return false;}

只需将它放在任何使用此函数的代码之前

这将验证函数是否存在,如果存在则执行

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

因此错误TypeError: me。onChange不是一个阻止的函数。

我有这样的情况,函数的名称根据添加到函数名中的变量(在本例中为var 'x')而变化。如此:

if ( typeof window['afunction_'+x] === 'function' ) { window['afunction_'+x](); } 
    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*/
    }

我有这个问题。If (obj && typeof obj === 'function'){…如果obj恰好未定义,}会不断抛出引用错误,所以最后我做了以下工作:

if (typeof obj !== 'undefined' && typeof obj === 'function') { ... }

然而,一位同事向我指出,检查它是否为!== 'undefined'然后=== 'function'是多余的,因此:

简单:

if (typeof obj === 'function') { ... }

更干净,工作得很好。