我的代码是

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


当前回答

我总是这样检查:

if(!myFunction){return false;}

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

其他回答

如何:

if('functionName' in Obj){
    //code
}

如。

var color1 = new String("green");
"length" in color1 // returns true
"indexOf" in color1 // returns true
"blablabla" in color1 // returns false

至于你的案子

if('onChange' in me){
    //code
}

请参阅MDN文档。

我喜欢用这个方法:

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
}

我已试过公认的答案;然而:

console.log(typeof me.onChange);

返回“定义”。 我注意到规范中声明了一个名为“onchange”的事件而不是“onchange”(注意camelCase)。

将原来接受的答案更改为以下对我有用:

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

试试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

试试这样做:

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

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

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