我的代码是

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


当前回答

这里有一个工作和简单的解决方案,检查一个函数的存在性,并由另一个函数动态触发该函数;

触发函数

function runDynamicFunction(functionname){ 

    if (typeof window[functionname] == "function") { //check availability

        window[functionname]("this is from the function it"); // run function and pass a parameter to it
    }
}

现在可以用PHP动态生成函数

function runThis_func(my_Parameter){

    alert(my_Parameter +" triggerd");
}

现在可以使用动态生成的事件调用该函数

<?php

$name_frm_somware ="runThis_func";

echo "<input type='button' value='Button' onclick='runDynamicFunction(\"".$name_frm_somware."\");'>";

?>

你需要的HTML代码是

<input type="button" value="Button" onclick="runDynamicFunction('runThis_func');">

其他回答

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

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

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

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

没有任何条件

me.onChange=function(){};

function getID( swfID ){
     if(navigator.appName.indexOf("Microsoft") != -1){
          me = window[swfID];
     }else{
          me = document[swfID];
     }
}

function js_to_as( str ){
     me.onChange(str);
}
function isFunction( o ) { return null !== o && "function" === typeof o && !!o.apply; }

试试这样做:

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

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

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