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.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

  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…

相關文章
相關標籤/搜索