我想要建立的是: 一个类Log,它有一个全局变量_level,表示当前的日志级别。 一个函数日志(level,msg),它将级别与_level进行比较,并决定是否打印msg。
用法如下:
Log.SetLevel(1); //global level
var logger1 = new Log();
logger1.log(0, "should print");
logger1.log(2, "should not print");
但是我无法完成它,似乎我对Javascript对象模型的理解存在一些问题,有人可以附上一个简单的代码吗?
答案 0 :(得分:1)
这应该有效:
function Log() {}
Log._level = Infinity; // Log all messages by default
Log.SetLevel = function (level) {
Log._level = level;
};
Log.prototype = {
log: function (level, message) {
if (level <= Log._level) {
console.log(message);
}
}
};
演示:
var logger1 = new Log();
logger1.log(0, "should print");
logger1.log(1, "should print");
logger1.log(2, "should print");
Log.SetLevel(1); //global level
logger1.log(0, "should print");
logger1.log(1, "should print");
logger1.log(2, "should not print");
答案 1 :(得分:1)
Javascript没有&#34;类&#34; ,但是,你可以创建一个构造函数并按照这样做
// create constructor
function Log() {}
// "global" Log level
Log.prototype.level = 0;
// Logger method
Log.prototype.log = function (level, message) {
return level === this.level ? alert(message) : false;
};
// change level method
Log.prototype.setLevel = function(level) {
// change level on constructor prototype
return this.constructor.prototype.level = level;
};
这是完成此操作的正确方法
var logger = new Log;
logger.setLevel(1)
logger.log(1, "should print");
logger.log(2, "should not print");
这样你也可以实际访问关卡,你不应该不必要地隐藏事物
答案 2 :(得分:1)
您可以执行以下操作,以保持&#34; global&#34;闭包中的 level ,并提供访问它的特权函数。
// Initialise the constructor
var Log = (function() {
// Keep level private in a closure
var _level = 0;
// Actual constructor function (it can be called anything)
function Log(){
/* constructor code here */
}
// Priviliged method to set the value of level
Log.setLevel = function(level) {
_level = level;
}
// Priviliged method to get the value of level
Log.getLevel = function() {
return _level;
}
// Assign Log to global variable Log
return Log;
}());
// Method inherited by all instances of Log
Log.prototype.log = function(level, msg) {
if (level <= Log.getLevel()) {
console.log(msg);
}
}
// Create some instances
var logger0 = new Log();
var logger1 = new Log();
// Set the level
Log.setLevel(1);
// Do some logging
logger0.log(1, 'should print 0'); // prints
logger0.log(2, 'should not print 0'); // doesn't print
logger1.log(1, 'should print 1'); // prints
logger1.log(2, 'should not print 1'); // doesn't print
console.log(Log.getLevel()); // 1
答案 3 :(得分:0)
您需要编写代码:
var logLevel = 1;
function Log() {
this.log = function (level, msg) {
if (level === logLevel) {
alert(msg);
}
else {
//Whatever you want to do
}
};
}
var logger1 = new Log();
logger1.log(1, "should print"); //will alert
logger1.log(2, "should not print"); //will not alert
alert(logLevel); //to prove that 'logLevel' is defined at a global level. The value is alerted signifying its scope to be at the global level
您可以在此处看到:http://jsfiddle.net/4f34c/1/
希望这有帮助!!!