阅读 269

IE8 两种全局函数定义会有所不同

Two global functions definition ways may be different under IE8

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.

不要定义全局函数(或变量)早已成为 JavaScript 开发中的一个常识。源于使用共享函数时,大量的全局定义可能会使得开发者深陷于变量定义冲突的问题,尤其是当项目像单页面应用(SPA,Single-page Applications)那样越来越庞大的时候,身同体会。

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.

然而,当你需要跟 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 怎么这么傲娇!!

You can't define the function globally with window:

竟不能通过 window 对象来定义全局函数:

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:

这就是为何我要在此进行文档记录,以告知诸位如何用下面的方式解决问题:

  1. Define it directly (only be suggested when not defining in global scope)

    直接定义(仅建议在非全局情况下使用)

    test = function (results) {
        /** handle with results */
    };
    复制代码
  2. 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…

关注下面的标签,发现更多相似文章
评论