JavaScript Factory Pattern
Blogs20142014-08-24
JavaScript Factory Pattern
I wrote an example of JavaScript factory pattern, it simulates to process xmlhttpresponse return:
var response = {};
response._200 = function() {
this.process = function(data) {
console.log('successful processing:', data);
}
}
response.done = function() {
console.log(this, arguments);
}
response._404 = function() {
this.process = function(data) {
response.done.apply(this, [data]);
}
}
response._302 = function() {
this.process = function(data) {
console.log("cached, redirect: ", data);
}
}
response._301 = function() {
this.process = function(data) {
response.factory(302).process.call(this, data);
//or:
(new response._302).process.call(this, data);
}
}
response.factory = function(type) {
return new response['_' + type];
}
var res = response.factory(200);
res.process('success'); //successful processing: success
res = response.factory(404);
res.process('failure');//response._404 {process: function} ["failure"]
res = response.factory(302);
res.process('redirect - 302');//cached, redirect: redirect - 302
res = response.factory(301);
res.process('redirect - 301');//cached, redirect: redirect - 301 