2015-06-06 12 views
0

我有一个稍微不寻常的模式,我试图实现,并没有完全弄明白。我的目标是如下创建一个名为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())的典型模式。但是,这种模式并没有达到我简单涉及直接调用函数的默认功能的简写目标。

甚至有可能吗?

回答

2

你可以这样来做

var debugLog = (function() { 
    var debugFlag = true; 

    function log() { 
    if (debugFlag) { 
     console.log.apply(null, arguments); 
    } else { 
     // production mode, nothing to log 
    } 
    }; 

    log.setDebugFlag = function(flag) { 
    debugFlag = flag; 
    } 
    return log; 
})(); 

module.exports = debugLog; 
+0

OP被谈论的NodeJS模块..这将是好的客户端 –

+0

好吧,我在年底添加了出口声明 – SpiderPig

+0

甜,谢谢! – Goblortikus

1

你可以使用闭合,就像这样:

// debugLog.js 
var debugFlag = true; 

function debugLog() { 
    if (debugFlag) { 
     console.log.apply(null, arguments); 
    } else { 
     // production mode, nothing to log 
    } 
} 

debugLog.setDebugFlag = function (newFlag) { 
    debugFlag = newFlag; 
} 

module.exports = debugLog; 

,并使用它像这样:

// otherFile.js 

var debugLog = require('./debugLog'); 
debugLog('Hey!'); 
debugLog.setDebugFlag(false); 
debugLog('This wont appear!'); 
+0

谢谢!这样做! – Goblortikus

+0

如果该模块中有更多功能,则缺少封装可能会导致问题。 – SpiderPig

+0

@SpiderPig它被完美封装用作NodeJS中的一个模块..比将其包装在不必要的IIFE中要好得多,这也将捕获任何“在该模块中的更多功能”的范围。 –

相关问题