Pergunta

We generally have the understanding that functions in javascript are used to execute blocks of code with a single call. 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?

Foi útil?

Solução

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;
   // ...
}

(E.g., 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.

Outras dicas

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. These tools can be used to optimize your JS files' size significantly, and you can keep your original code readable.

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();
}());
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top