如何检查JavaScript中是否存在函数? [英] How to check if function exists in JavaScript?

查看:139
本文介绍了如何检查JavaScript中是否存在函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我跟着本指南创建一个新的JS到Flash通信。

I followed this guide to create a new JS to flash communication.

我的代码是

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错误

However, sometimes my onChange does not load. Firebug errors with


me.onChange不是函数

me.onChange is not a function

我想优雅地降级,因为这不是我程序中最重要的功能。 typeof 给出了同样的错误。

I want to degrade gracefully because this is not the most important feature in my program. typeof gives the same error.

关于如何确保它存在然后只执行<$的任何建议c $ c> onChange ?

Any suggestions on how to make sure that it exists and then only execute onChange?

(以下所有方法除了尝试捕捉一项工作)

(None of the methods below except try catch one work)

推荐答案

尝试这样的事情:

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

或更好(根据UpTheCreek赞成评论)

or better yet (as per UpTheCreek upvoted comment)

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

这篇关于如何检查JavaScript中是否存在函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆