我想使用modified version of this solution来将控制台日志记录包装到新功能中:
var user = {
username,
password,
confirm,
};
function check(a) {
if (user.username != "") {
return true
}
if (6 < user.password < 30) {
return true
}
if (user.password = user.confirm) {
return true
} else {
document.write("wrong");
return false
}
console.log(user = {
username = "adc",
password = "sadcddddddcdcdcdcdcdcdcđcdcdcdcdcdc",
confirm = "sadcddddddcdcdcdcdcdcdcđcdcdcdcdcdc",
};);
}
但是,我希望不创建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");
的新实例,并将Logger
与相关true/false
一起传递。我尝试在另一个函数中包装新实例,但我必须使用其中的特定方法:
string
我怎么能重构这个,所以我可以打电话:
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.
答案 0 :(得分:1)
我认为这符合您的要求。如果您正在寻找更多或其他内容,请告诉我。
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