Javascript 带有noop的节点控制台包装器
我想使用,将控制台登录包装到一个新函数中:Javascript 带有noop的节点控制台包装器,javascript,node.js,console,Javascript,Node.js,Console,我想使用,将控制台登录包装到一个新函数中: function Logger(force) { const logging = {}; if (force) { for (let m in console) { if (typeof console[m] == 'function') { logging[m] = console[m].bind(console); }
function Logger(force) {
const logging = {};
if (force) {
for (let m in console) {
if (typeof console[m] == 'function') {
logging[m] = console[m].bind(console);
}
}
} else {
for (let m in console) {
if (typeof console[m] == 'function') {
logging[m] = function() {};
}
}
}
return logging;
}
debugOff = new Logger(false);
debugOff.log("this WILL NOT log");
debugOn = new Logger(true);
debugOn.log("This WILL log");
但是,我不想创建记录器的新实例,只想用相关的字符串传递true/false
。我已尝试将新实例包装到另一个函数中,但我必须在其中使用特定的方法:
function noopLogger (force, string) {
function Logger(force) {
const logging = {};
if (force) {
for (let m in console) {
if (typeof console[m] == 'function') {
logging[m] = console[m].bind(console);
}
}
} else {
for (let m in console) {
if (typeof console[m] == 'function') {
logging[m] = function() {};
}
}
}
return logging;
}
instance = new Logger(force);
return instance.log(string); // don't want to do this here
}
noopLogger(true, "this will log"); // this logs, but I only have access to log, not warn, error, etc.
我如何重构它,以便调用:
noopLogger.log(true, 'this WILL log');
noopLogger.log(false, 'this WILL NOT log');
我认为这符合你的要求。让我知道,如果你正在寻找更多或其他东西
function getLogger() {
const logger = {};
for (let m in console) {
if (typeof console[m] == 'function') {
logger[m] = function (force, string) {
if (!force) return;
console[m].call(console, string);
}
}
}
return logger;
}
const noopLogger = getLogger();
noopLogger.log(true, 'this WILL log');
noopLogger.log(false, 'this WILL NOT log');
noopLogger.warn(true, 'this warning WILL log');
noopLogger.warn(false, 'this warning WILL NOT log');
输出:
:> node test.js
this WILL log
this warning WILL log
logger[m]=function(force,string)
是我一直无法理解的表达式。我在装订上被挂断了。这非常像@Neeraj Sharma