我的代码是

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


当前回答

//Simple function that will tell if the function is defined or not
function is_function(func) {
    return typeof window[func] !== 'undefined' && $.isFunction(window[func]);
}

//usage

if (is_function("myFunction") {
        alert("myFunction defined");
    } else {
        alert("myFunction not defined");
    }

其他回答

这段简单的jQuery代码应该可以做到:

if (jQuery.isFunction(functionName)) {
    functionName();
}

我怀疑我没有正确地分配onload。

将get_ID调用移动到onclick事件中应该会解决这个问题。

显然,你可以进一步陷阱,如前所述:

function js_to_as( str) {
  var me = get_ID('jsExample');
  if (me && me.onChange) {
    me.onChange(str);
  }
}

我总是这样检查:

if(!myFunction){return false;}

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

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

js库在isFunction方法中这样定义它(评论认为这可能会迎合一些浏览器错误)

typeof obj == 'function' || false

http://underscorejs.org/docs/underscore.html#section-143