IE8 兩種全域性函式定義會有所不同

aleen42發表於2019-02-13

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…

相關文章