Skip to content

Instantly share code, notes, and snippets.

@KJlmfe
Created April 24, 2014 06:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KJlmfe/11244036 to your computer and use it in GitHub Desktop.
Save KJlmfe/11244036 to your computer and use it in GitHub Desktop.
JavaScript 设计模式 - Factory(工厂模式) - 运行时确定创建对象
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