Created
June 2, 2011 22:57
-
-
Save onteria/1005522 to your computer and use it in GitHub Desktop.
Function returning object versus object constructor
This file contains 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 fs = require('fs'); | |
var http = require('http'); | |
function MyServer(config_file) { | |
return { | |
config: {}, | |
StartServer: function() { | |
http.createServer((function (req, res) { | |
this.SendResponse(res); | |
}).bind(this)).listen(this.config.port, this.config.host, function() { | |
console.log("Server is bound.") | |
}); | |
}, | |
SendResponse: function(response) { | |
response.writeHead(200, {'Content-Type': 'text/plain'}); | |
response.end('Hello World\n'); | |
}, | |
ParseConfig: function(err,json_string) { | |
if(err) { | |
console.error("Could not open config file: ", err); | |
process.exit(1); | |
} | |
try { | |
console.log(json_string); | |
this.config = JSON.parse(json_string); | |
this.StartServer(); | |
} | |
catch(exception) { | |
console.error("There was an error parsing the json config file: ", exception); | |
process.exit(1); | |
} | |
}, | |
SetupServer: function() { | |
fs.readFile(config_file, 'utf8', this.ParseConfig.bind(this) ); | |
} | |
} | |
} | |
var server = MyServer('config.json'); | |
server.SetupServer(); | |
//vs | |
var fs = require('fs'); | |
var http = require('http'); | |
function MyServer(config_file) { | |
this.config = {}; | |
this.StartServer = function() { | |
http.createServer((function (req, res) { | |
this.SendResponse(res); | |
}).bind(this)).listen(this.config.port, this.config.host, function() { | |
console.log("Server is bound.") | |
}); | |
}; | |
this.SendResponse = function(response) { | |
response.writeHead(200, {'Content-Type': 'text/plain'}); | |
response.end('Hello World\n'); | |
}; | |
this.ParseConfig = function(err,json_string) { | |
if(err) { | |
console.error("Could not open config file: ", err); | |
process.exit(1); | |
} | |
try { | |
console.log(json_string); | |
this.config = JSON.parse(json_string); | |
this.StartServer(); | |
} | |
catch(exception) { | |
console.error("There was an error parsing the json config file: ", exception); | |
process.exit(1); | |
} | |
}; | |
fs.readFile(config_file, 'utf8', this.ParseConfig.bind(this) ); | |
} | |
var server = new MyServer('config.json'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment