我按照本指南建立了一个用于通信的新JS。 app
个人代码是 函数
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
没法加载。 萤火虫错误 spa
me.onChange不是一个函数 code
我想优雅地降级,由于这不是我程序中最重要的功能。 typeof
给出相同的错误。 事件
关于如何确保它存在而后仅执行onChange
任何建议? get
(如下任何一种方法都不能尝试抓到一件做品) io
function js_to_as( str ){ if (me && me.onChange) me.onChange(str); }
尝试这样的事情: function
if (typeof me.onChange !== "undefined") { // safe to use the function }
或更好(根据UpTheCreek的评论) cli
if (typeof me.onChange === "function") { // safe to use the function }
无条件 bug
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); }
我会怀疑me
没有正确分配onload。
将get_ID调用移到onclick事件中应该注意这一点。
显然,您能够如前所述进一步陷井:
function js_to_as( str) { var me = get_ID('jsExample'); if (me && me.onChange) { me.onChange(str); } }
我将更进一步以确保该属性确实是一个函数
function js_to_as( str ){ if (me && me.onChange && typeof me.onChange === 'function') { me.onChange(str); } }