我的代码是

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 (obj && typeof obj === 'function'){…如果obj恰好未定义,}会不断抛出引用错误,所以最后我做了以下工作:

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

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

简单:

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

更干净,工作得很好。

其他回答

对我来说,最简单的方法是:

function func_exists(fname)
{
  return (typeof window[fname] === 'function');
}

我将进一步确认这个属性确实是一个函数

function js_to_as( str ){
     if (me && me.onChange && typeof me.onChange === 'function') {
         me.onChange(str);
     }
}
// just pass your tested function name instead of myFunctionName
if ( $.isFunction($.fn.myFunctionName) ) {
    console.log( 'write your code here.' );
}

如何:

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文档。

试试这个:

Window.function_exists=function(function_name,scope){
//Setting default scope of none is provided
If(typeof scope === 'undefined') scope=window;
//Checking if function name is defined
If (typeof function_name === 'undefined') throw new 
Error('You have to provide an valid function name!');
//The type container
var fn= (typeof scope[function_name]);
//Function type
If(fn === 'function') return true;
//Function object type
if(fn.indexOf('function')!== false) return true; 
return false;
}

请注意,这是我用手机写的 可能包含一些大写问题和/或其他需要的更正,例如函数名

如果你想让PHP这样的函数检查是否设置了var:

Window.isset=function (variable_con){
If(typeof variable_con !== 'undefined') return true;
return false;
}