我的代码是

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


当前回答

没有看到这个建议: 我。onChange && me.onChange(str);

基本上如果我。onChange是未定义的(如果它没有被初始化,它将是未定义的),那么它将不会执行后面的部分。如果我。onChange是一个函数,它将执行me.onChange(str)。

你甚至可以更进一步,这样做:

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

以防我也是异步的。

其他回答

如果你正在使用eval将一个字符串转换为函数,并且你想检查这个eval方法是否存在,你会想在eval中使用typeof和你的函数字符串:

var functionString = "nonexsitantFunction"
eval("typeof " + functionString) // returns "undefined" or "function"

不要反过来尝试一种类型的eval。如果你这样做,ReferenceError将被抛出:

var functionString = "nonexsitantFunction"
typeof(eval(functionString)) // returns ReferenceError: [function] is not defined

没有任何条件

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 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');">
    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*/
    }

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