I wrote the following code to implement logging in a separate js logger.js file using OOP.
var console; function Logger() { init(); } var init = function() { if(!window.console){ console = { log: function(message){}, info: function(message){}, warn: function(message){}, error: function(message){} }; } else { console = window.console; } }; Logger.prototype.log = function(message) { console.log(message); } Logger.prototype.logInfo = function(message) { console.info(message); } Logger.prototype.logWarn = function(message) { console.warn(message); } Logger.prototype.logError = function(message) { console.error(message); }
I use it from another js file, site.js, like:
var logger = new Logger(); //global variable var getComponentById = function(id) { var component = null; if(id) { try { component = AdfPage.PAGE.findComponentByAbsoluteId(id); }catch(e){ logger.logError(e); } } return component; }
It was interesting to me
- If I implemented the
Logger class correctly, supporting OOP JavaScript. - Will it handle a scenario in which the browser does not have a console?
- How can I make the
init() method inaccessible from another js file or method? I mean, how can I make this private ?
Any pointer would be very helpful to me.
Update
From another SO thread, I found information about a private method, and I changed my approach:
function Logger() { init(); } Logger.prototype = (function() { var console; var init = function() { if(!window.console){ this.console = { log: function(message){}, info: function(message){}, warn: function(message){}, error: function(message){} }; } else { this.console = window.console; } }; return { constructor: Logger, log: function(message) { this.console.log(message); }, logInfo: function(message) { this.console.info(message); }, logWarn: function(message) { this.console.warn(message); }, logError: function(message) { this.console.error(message); } }; })();
But in this case, I get an error that init not defined.
source share