开发者

I'm playing around with different design patterns in Javascript. This factory has got me confused

开发者 https://www.devze.com 2023-01-09 08:49 出处:网络
I\'m playing around with different JS design patterns, and im trying to modify some samples I\'ve seen out there.I saw an example of a xhr开发者_JAVA百科 factory, that had several nested try/catch sta

I'm playing around with different JS design patterns, and im trying to modify some samples I've seen out there. I saw an example of a xhr开发者_JAVA百科 factory, that had several nested try/catch statements that were nested within eachother.

try{
...
}catch(e){
    try{
    ...
    }catch(e){}
}

I figured I'd be able to do a self-invoking function. However It seems to have eluded me as to how it should work. Does anyone have any advice?

Example:

http://jsfiddle.net/jiggliemon/a7xWq/2/


[Update]:

http://jsfiddle.net/jiggliemon/b5LaZ/embedded/

Case Closed.


Changed try loop to:

for(var i = 0, l = instances.length; i < l; i ++) {
    try{
        var obj = instances[i].getInstance();
        return instances[i];
    }catch(e){ }
}

Full code


var XHR = (function(){
    var ins = [
        function(){return new XMLHttpRequest();},
        function(){return new ActiveXObject('Msxml2.XMLHTTP');},
        function(){return new ActiveXObject('Microsoft.XMLHTTP');}
    ],i,tmp;

    return (function tryIns(i){
        i = i || 0;
        while(i < ins.length){
            try{tmp = ins[i]();}
            catch(e){i++; tryIns(i);}
            finally{return ins[i];}
        }
        throw new Error("Your browser doesn\'t support Ajax requests");
    })();
})();
0

精彩评论

暂无评论...
验证码 换一张
取 消