我的代码是

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


当前回答

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

console.log(typeof me.onChange);

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

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

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

其他回答

// just pass your tested function name instead of myFunctionName
if ( $.isFunction($.fn.myFunctionName) ) {
    console.log( 'write your code here.' );
}

我建议使用:

function hasMethod(subject, methodName) {
  return subject != null && typeof subject[methodName] == "function";
}

第一个检查主题!= null过滤掉没有任何属性的null值(null和undefined)。如果没有这个检查,主题[methodName]可能会抛出一个错误:

TypeError:(undefined|null)没有属性

只检查一个真值是不够的,因为0和""都是假的,但确实有属性。

在确认subject不是null之后,你可以安全地访问属性并检查它是否匹配typeof subject[methodName] == "function"。


将此应用到您的代码,您现在可以做到:

if (hasMethod(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
}

试试这个:

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;
}

为了说明前面的答案,这里有一个快速的JSFiddle代码片段:

function test () { console.log() } console.log(typeof test) // >> "function" // implicit test, in javascript if an entity exist it returns implcitly true unless the element value is false as : // var test = false if(test){ console.log(true)} else{console.log(false)} // test by the typeof method if( typeof test === "function"){ console.log(true)} else{console.log(false)} // confirm that the test is effective : // - entity with false value var test2 = false if(test2){ console.log(true)} else{console.log(false)} // confirm that the test is effective : // - typeof entity if( typeof test ==="foo"){ console.log(true)} else{console.log(false)} /* Expected : function true true false false */