我的代码是

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


当前回答

试试typeof——用'undefined'表示它不存在,用'function'表示函数。这段代码的JSFiddle

function thisishere() {
    return false;
}
alert("thisishere() is a " + typeof thisishere);
alert("thisisnthere() is " + typeof thisisnthere);

或作为if:

if (typeof thisishere === 'function') {
    // function exists
}

或者在一行中返回一个值:

var exists = (typeof thisishere === 'function') ? "Value if true" : "Value if false";
var exists = (typeof thisishere === 'function') // Returns true or false

其他回答

放两个感叹号,即!!在要检查的函数名之前。如果它存在,它将返回true。

function abc(){
}
!!window.abc; // return true
!!window.abcd; // return false

如果你正在使用eval将一个字符串转换为函数,并且你想检查这个eval方法是否存在,你会想在eval中使用typeof和你的函数字符串:

var functionString = "nonexsitantFunction"
eval("typeof " + functionString) // returns "undefined" or "function"

不要反过来尝试一种类型的eval。如果你这样做,ReferenceError将被抛出:

var functionString = "nonexsitantFunction"
typeof(eval(functionString)) // returns ReferenceError: [function] is not defined

我喜欢用这个方法:

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
}
function js_to_as( str ){
     if (me && me.onChange)
         me.onChange(str);
}

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

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

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