我的代码是

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之外都没有)


当前回答

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

if ( typeof window['afunction_'+x] === 'function' ) { window['afunction_'+x](); } 

其他回答

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

试试这样做:

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

或者更好(根据upcreek的upvotes评论)

if (typeof me.onChange === "function") { 
    // safe to use the function
}
    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*/
    }

简单来说就是:捕捉异常。

我真的很惊讶在这篇文章中没有人回答或评论异常捕获。

细节:这里有一个例子,我试图匹配一个函数,前缀为mask_,后缀为表单字段“name”。当JavaScript没有找到该函数时,它应该抛出一个ReferenceError,您可以在catch部分进行处理。

函数inputMask(input) { 尝试{ let maskedInput = eval("mask_"+input.name); if(typeof maskedInput === "undefined") 返回input.value; 其他的 返回eval(“mask_”+ input.name)(输入); } catch(e) { if (e instanceof ReferenceError) { 返回input.value; } } }

我喜欢用这个方法:

function isFunction(functionToCheck) {
  var getType = {};
  return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}

用法:

if ( isFunction(me.onChange) ) {
    me.onChange(str); // call the function with params
}