#ifndef in javascript
If you have some build script I suggest to use GPP preprocessor(http://en.nothingisreal.com/wiki/GPP, or win version http://makc.googlecode.com/svn/trunk/gpp.2.24-windows/)
So you need to do the following steps:
- gpp -o _script.js script.js (where _script.js - your source file with preprocessor commands)
- (OPTIONAL) minify script.js (using google closure compiler, etc.)
- deploy script.js to your web folder.
In this case you'll get the most optimized js code. And you do not need runtime checks
#define debugMode
#ifdef debugMode
var myFunc = function(a,b) {
// body of your function here
}
#else
var myFunc = function(a,b) {
// body of your alternate function here
}
#endif
As I presume you know, Javascript doesn't have preprocessor directives like C/C++, but you can use regular if
statements that are evaluated at run-time like this:
if (typeof myFunc === "undefined") {
var myFunc = function(a,b) {
// body of your function here
}
}
or for a whole library of functions:
if (!window.controlUtilsDefined) {
window.controlUtilsDefined = true;
// put control library functions here
function aaa() {
// body here
}
function bbb() {
// body here
}
}
or if you want to check based on some other variable:
var myFunc;
if (debugMode) {
myFunc = function(a,b) {
// body of your function here
}
} else {
myFunc = function(a,b) {
// body of your alternate function here
}
}
If your concern is just that you have multiple copies of the exact same function names in the library that each control uses, that isn't technically a problem in Javascript. The last defined one will be the operative one, but if they're all the same that isn't technically a problem. Only one definition will exist in memory as the later definitions will replace the earlier ones.
If you control the source of the controls, then it would be better to break the common utilities out separately into their own JS file and have the host page just include that utilities script file once.
Or (with a little more work but no additional responsibilities for the host page), each control could dynamically load their utlities from an external JS file and check a known global variable to see if some other control has already loaded the common external JS.