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

IE8下全局函数定义
本文探讨了在IE8浏览器中定义全局函数的不同方式及其潜在问题,特别是在与IE插件进行交互时。提供了两种有效的工作绕过方法。

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…

转载于:https://juejin.im/post/5a95239a6fb9a0635f7ea5e0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值