我已经编写了以下代码,使用面向对象编程在单独的js文件logger.js中实现日志记录。
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);
}
我正在另一个js文件site.js中使用它:
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;
}
我想知道:
- 如果我已经按照JavaScript面向对象编程的规范实现了
Logger
类,那么它是否能处理浏览器没有控制台的情况? - 如何使
init()
方法无法从其他JavaScript文件或方法中访问?我的意思是如何将其设置为private
?
任何指针都对我有很大帮助。
更新
从另一个SO线程中,我找到了有关私有方法的信息,并改变了我的方法:
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);
}
};
})();
但是在这种情况下,我遇到了一个错误,即
init
未定义。