This page looks plain and unstyled because you're using a non-standard compliant browser. To see it in its best form, please visit upgrade to a browser that supports web standards. It's free and painless.

Fillano's Learning Notes 會員登入 會員註冊

« 上一篇 | 下一篇 »

最近需要修改以前寫過的試算網頁,就把舊的code拿出來看了一下,試跑時發現裡面用的取得XmlHttpRequest物件的方法不是很有效率。因為我沒有用到非同步機制,只是把他當作一個動態IO的方法,其實不需要使用多個XmlHttpRequest物件,所以就想把他改寫成Singleton。

舊的方法是我從mozilla網站上抄來的,像這樣:

function xmlhttp() {
    try{ return new ActiveXObject("Msxml2.XMLHTTP.6.0") }catch(e){}
    try{ return new ActiveXObject("Msxml2.XMLHTTP.3.0") }catch(e){}
    try{ return new ActiveXObject("Msxml2.XMLHTTP") }catch(e){}
    try{ return new ActiveXObject("Microsoft.XMLHTTP") }catch(e){}
    try{ return new XMLHttpRequest();} catch(e){}
    return null;
}

這樣每次執行xmlhttp函數來取得XmlHttpRequest物件時,都要跑過幾次try catch。但是把他改寫成這樣的話,就有singleton的效果了:

var xmlhttp = function() {
    var ajax = function() {
        try{ return new ActiveXObject("Msxml2.XMLHTTP.6.0") }catch(e){}
        try{ return new ActiveXObject("Msxml2.XMLHTTP.3.0") }catch(e){}
        try{ return new ActiveXObject("Msxml2.XMLHTTP") }catch(e){}
        try{ return new ActiveXObject("Microsoft.XMLHTTP") }catch(e){}
        try{ return new XMLHttpRequest();} catch(e){}
        return null;
    }();
    return function(){return ajax;};
}();

這樣要用到的變數在一開始就產生了,所以呼叫函數的時候其實只是把這個變數回傳而已。

  1. Re: 用Closure模仿Singleton [回覆]

    用金银工艺礼品铜、铁、锡等金属材料,或以网易企业邮箱金属材料为主辅以其他滤布材料,加工搜索引擎优化制作而成的seo工艺品。具有挂历厚重、雄浑、电脑包华贵、高档礼品典雅、精细的风格。

    fefe 回應於 08 元月, 2010 13:24

  2. Re: 用Closure模仿Singleton [回覆]

    但是这样总是使用一份xmlhttp实例是不是不能满足一些效果呢?..比如同时发送多个提交...

    Dreampuf 回應於 09 元月, 2010 18:40

發表回應

 暱稱 (必填)

 標題

 個人網頁

 電子郵件

authimage 
 認證碼 (必填)