1

在 C++ 中,您可以通过使用预处理指令来省略编译调试代码,以保持编译代码快速且不受生产中不需要的调试代码的阻碍。

在 JavaScript 中是否有相关的方法来做到这一点?我过去一直在做的是注释掉调试代码,但我想要一种更简洁的方式来做到这一点。

下面的示例显示了 4 个 if 语句,它们在 debug 设置为 true 时激活。但是在生产中,当我知道它将被设置为 false 时,我不希望它被检查 4 次。正如我所提到的,我可以将它塞进一行并将其注释掉......但我想要一种干净的方式来做到这一点?

/**
 **  cType
 */

function cType( o_p ) {
    if( debug ) {
        var t1, t2, t3, t4, i1, i2, i3; t1 = new Date().getTime();
    }
    o_p = MType[ o_p.model ].pre( o_p ); 
    if ( o_p.result !== 'complete' ) {
        if( debug ) {
            t2 = new Date().getTime();
            console.log( '---------------Send to Server - object_pipe: \n ' + o_p.toSource() ); 
        } 
        var string_pipe = JSON.stringify( o_p );
        cMachine( 'pipe=' + string_pipe , function( string_pipe ) {
            if( debug ) { 
                console.log( '---------------Receive from Server - object_pipe: \n ' + string_pipe ); 
                t3 = new Date().getTime();
            }
            MType[ o_p.model ].post( JSON.parse( string_pipe ) );
            if( debug ) {
                t4 = new Date().getTime(); i1 = t2-t1 ; i2 = t3-t2 ; i3 = t4-t3;
                console.log( '---------------Pre, Transit, Post = ', i1, i2, i3 );  
            }
        } );
    }
}
4

3 回答 3

2

您始终可以通过 c 预处理器传递它,例如:

gcc -E input.js -o output.js

这将允许您使用#if 甚至包括和宏。

于 2012-07-08T16:11:43.060 回答
1

如果您使用RequireJS,您可以使用构建编译指示甚至has.js 集成在优化(缩小)时禁用/启用代码片段。

于 2012-07-08T16:14:18.380 回答
0

不,Javascript 没有被编译,它被解释了。因此,除非您传递非标准的 Javascript,否则不可能有预处理指令——它可能不再是 Javascript——通过另一个实用程序编写代码。

于 2012-07-08T16:10:39.830 回答