我的代码是

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


当前回答

如果你正在检查一个函数是否是jQuery插件,你需要使用$.fn.myfunction

if (typeof $.fn.mask === 'function') {
    $('.zip').mask('00000');
}

其他回答

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

我有这个问题。If (obj && typeof obj === 'function'){…如果obj恰好未定义,}会不断抛出引用错误,所以最后我做了以下工作:

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

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

简单:

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

更干净,工作得很好。

为了说明前面的答案,这里有一个快速的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 */

我建议使用:

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

现代JavaScript来拯救!

me.onChange?.(str)

可选链接语法(?.)解决了这个问题

从ES2020开始使用JavaScript 在Typescript版本3.7

在上面的例子中,如果a me。onChange属性存在并且是一个函数,它被调用。

如果没有我。onChange属性存在,则什么也不发生:表达式只是返回undefined。

注——若有我。onChange属性存在但不是函数,将抛出TypeError,就像在JavaScript中调用任何非函数作为函数一样。可选的链接不做任何魔法,使这个消失。