As a common sense of coding JavaScript, it is not a wise choice to define functions (or variables) globally, as developers struggle with definning conflict problems when using shared functions, especially when the project has become larger and larger, like SPA.git
不要定义全局函数(或变量)早已成为 JavaScript 开发中的一个常识。源于使用共享函数时,大量的全局定义可能会使得开发者深陷于变量定义冲突的问题,尤为是当项目像单页面应用(SPA,Single-page Applications)那样愈来愈庞大的时候,身同体会。github
However, it seems to be the only one choice when you have to communicate with IE add-ons. For example, I have a task needing add-ons to handle asynchronously, and tell the result to me with a callback method named done(result)
. In such a case, the most common way you may meet is where add-ons developers use FireBreath to implement this. With this framework, you may have to define a global function, and pass the string of the function name to add-ons, so that they can callback result for you with calling your defined functions.app
然而,当你须要跟 IE 插件进行数据交互时,定义全局函数彷佛是惟一可行的方法。举个例子来讲,我须要插件异步处理一个任务,并经过回调告诉我结果。这种状况下,最寻常的作法是插件开发者会使用 FireBreath 来实现,而该框架下,你须要定义一个全局函数,并把函数名以字符串的形式传递给插件。这样,插件才能把结果回调至你所定义的函数。框架
function scope() {
/** function scope but not global one */
document.getElementById('#ie-plugin').runJSFunc('test', result); /** nothing happens */
/** throw "Method Invoke Failed" */
function test(result) {
/** handle with result */
};
}
复制代码
Ooops, there is something wrong under IE8!!异步
不会吧,IE8 怎么这么傲娇!!async
You can't define the function globally with window
:函数
竟不能经过 window
对象来定义全局函数:oop
try {
document.getElementById('#ie-plugin').runJSFunc('test', result);
} catch (e) {
console.log(e.message); /** => Method Invoke Failed. */
}
/** throw "Method Invoke Failed" */
window.test = function (results) {
/** handle with results */
};
复制代码
That's why I marked this with documenting here, in order to tell you how to solve this with following workarounds:ui
这就是为什么我要在此进行文档记录,以告知诸位如何用下面的方式解决问题:this
Define it directly (only be suggested when not defining in global scope)
直接定义(仅建议在非全局状况下使用)
test = function (results) {
/** handle with results */
};
复制代码
Use the official simple way (only use when it is in the global scope)
使用官方简单的函数定义(仅局限于全局做用域下使用)
function test(results) {
/** handle with results */
}
复制代码
更多 IE 下的疑难杂症可参考:github.com/aleen42/Per…