我有一个稍微不寻常的模式,我试图实现,并没有完全弄明白。我的目标是如下创建一个名为DEBUGLOG作为一个灵活的console.log替换功能,它可以被称为:如何使用默认功能和持久属性创建JavaScript函数构造函数?
debugLog('thing to log #1', 'thing to log #2', objectToLog1, objectToLog2);
^^则params的数量应该是任意的,就像是可能的console.log
这就是我所说的“默认”功能。现在我还想通过属性函数添加一些附加功能。
例子:
debugLog.setDebugFlag(true); // sets the internal this.debugFlag property to true or false depending on param
我试图做到这一点的节点和我有什么到目前为止并没有完全让我实现这个模式:
var debugLog = function() {
this.debugFlag = this.debugFlag || true;
if (this.debugFlag) {
console.log.apply(null, arguments);
} else {
// production mode, nothing to log
}
};
debugLog.prototype.setDebugFlag = function (flagBool) {
this.debugFlag = flagBool;
}
module.exports = new debugLog();
该模块将包括使用标准需求模式的Node应用程序:
var debugLog = require('./debugLog.js');
问题是我该如何实现s函数对象的默认功能模式,还扩展了“属性”风格的功能?请注意我已经意识到所有功能都来自函数属性(如debugLog.log()和debugLog.setDebugFlag())的典型模式。但是,这种模式并没有达到我简单涉及直接调用函数的默认功能的简写目标。
甚至有可能吗?
OP被谈论的NodeJS模块..这将是好的客户端 –
好吧,我在年底添加了出口声明 – SpiderPig
甜,谢谢! – Goblortikus