简体   繁体   English

Javascript压缩-在一行中定义许多变量

[英]Javascript condensing - defining many variables in one line

We generally have the understanding that functions in javascript are used to execute blocks of code with a single call. 我们通常了解到,使用javascript中的函数可以通过一次调用来执行代码块。 However, I'm currently working in a system that contains many functions which require many variables to be defined, so I'm seeing a lot of repeat code. 但是,我目前正在一个包含许多功能的系统中工作,这些功能需要定义许多变量,因此我看到了很多重复代码。 I'd love to put the variable declarations in a function so they don't take a whole bunch of space, but is something similar to that even possible? 我很想将变量声明放在函数中,这样它们就不会占用一整堆空间,但是是否有可能这样做呢?

I'd love to put the variable declarations in a function so they don't take a whole bunch of space, but is something similar to that even possible? 我很想将变量声明放在函数中,这样它们就不会占用一整堆空间,但是是否有可能这样做呢?

If you mean: 如果你的意思是:

function one() {
   var a, b, c, d, e, f;
   // ...
}
function two() {
   var a, b, c, d, e, f;
   // ...
}

(Eg, each function has its own copy of the variables.) (例如,每个函数都有其自己的变量副本。)

...and you want ...而你想要

// Doesn't work
function declare() {
   var a, b, c, d, e, f;
}
function one() {
    declare();
    // ...use a, b, etc. here
}
function two() {
    declare();
    // ...use a, b, etc. here
}

No, you cannot do that. 不,你不能那样做。

You might consider encapsulating the variables in an object, if the same set of variables is used in multiple places. 如果在多个位置使用相同的变量集,则可以考虑将变量封装在对象中。 In fact, the whole thing sounds like it might be refactored as an object. 实际上,整个事情听起来好像可以重构为一个对象。

But without too much refactoring: 但无需过多重构:

function declare() {
    return {
        a: /*...*/,
        b: /*...*/,
        c: /*...*/,
        d: /*...*/,
        e: /*...*/,
        f: /*...*/,
    };
}
function one() {
    var o = declare();
    // ...use o.a, o.b, etc.
}
function two() {
    var o = declare();
    // ...use o.a, o.b, etc.
}

But again, that's the minimal-impact solution. 但这又是影响最小的解决方案。 It's like that if you look at your overall code with the idea that you could organize things a bit into objects, you'd find a less artificial way than the above. 就像如果您以可以将事物稍微组织成对象的方式查看整体代码时,会发现比上述方法更少的人为方式。

If I understood correctly what you want to do, it's probably best not to do it manually. 如果我正确理解了您想做什么,最好不要手动进行。 You can just use a minifier, such as uglify or Google's Closure Compiler. 您可以只使用一个缩小器,例如uglify或Google的Closure Compiler。 These tools can be used to optimize your JS files' size significantly, and you can keep your original code readable. 这些工具可用于极大地优化JS文件的大小,并使原始代码可读。

There are several solutions, perhaps the simplest one is just relying on closures: 有几种解决方案,也许最简单的解决方案只是依靠闭包:

(function(){}
    // declare all vars here
    var a = 1, b = 2;

    // var a will be available here
    function foo() {
        alert(a);
    }

    foo();
}());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM