Is there a way that I can define a macro similar to C/C++ macros in Javascript?
I want to use this for debug statements:
Something like
#ifdef TEST__
#define MYDEBUG(##x) debug(__FILE__,x)
#else
#define debug
#endif
Not necessarily similar, but I want to acheieve that functionality. Is there a way I can do that?
Thanks
var de = false; // true when debugging
function bug( msg ){ ... display msg ... }
Usage:
de&&bug( "hello world")
When "de" is false (production mode), the overhead is minimal.
There isn't a way to do this in JavaScript. You could have a global variable like
var isDebugging = false;
Then when writing code, just check if the variable is true. Obviously this will create some unwanted overhead with file size, and a very slight performance loss. But other than specifying your own format, and running the code though a tool to strip debugging code out before you upload.
Something like
var foo = function() {
<!-- document.write( "blah" ); -->
};
For a release build, you would remove everything inside the tags, inclusive. And for a debug build you could just remove the tags, but keep the code. Something like this could be performed with an Ant build script or similar.
Javascript has no macros since there is no compiler. You could use console.log
and write a regex to strip those statements when deploying.
While is true that there is no compile time as @sapht said, you can pre-process your files if you want. Typically I use an ant script to combine many Javascript files together and add build information.
From a google search I see there is a Javascript preprocessor that you may find interesting: http://www.bramstein.com/projects/preprocess/
For those who are still interested:
https://github.com/dcodeIO/Preprocessor.js
A JavaScript source file preprocessor in pure JavaScript, e.g. to build different versions of a library.
Examples:
// #ifdef FULL
console.log("Including extension");
// #include "path/to/extension.js"
// #else
console.log("Not including extension");
// #endif
// #if 1==2
console.log("1==2");
// #elif 2==2
console.log("2==2");
// #endif
With Builder – https://github.com/electricimp/Builder, you can do like:
@macro MYDEBUG(x)
debug(@{__FILE__}, @{x});
@end
...
@{MYDEBUG(100500)}
Also supports for includes directly from GitHub.