Created
April 24, 2014 06:46
-
-
Save KJlmfe/11244036 to your computer and use it in GitHub Desktop.
JavaScript 设计模式 - Factory(工厂模式) - 运行时确定创建对象
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var SimpleHandler = function() { }; | |
SimpleHandler.prototype = { | |
request: function(method, url, callback, postVars) { | |
var xhr = this.createXhrObject(); | |
xhr.onreadystatechange = function() { | |
// do some things | |
}; | |
xhr.open(method. url, true); | |
xhr.send(postVars); | |
}, | |
createXhrObject: function() { | |
var methods = [ | |
function() { return new XMLHttpRequest(); }, | |
function() { return new ActiveObject("Msxml2.XMLHTTP"); }, | |
function() { return new ActiveObject("Miscrosoft.XMLHTTP"); } | |
]; | |
for(var i=0, len = methods.lenght; i < len; i++ ) { | |
try { | |
methods[i](); | |
} catch(e) { | |
continue; | |
} | |
// 修改自己 以免再次执行上面的检测代码 | |
this.createXhrObject = methods[i]; // Memoize the method | |
return methods[i]; | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment