开发者

JavaScript - where to declare variables and define functions?

开发者 https://www.devze.com 2023-04-05 12:20 出处:网络
Which is better: var foo = 0, fnFoo = function (bar) { \"use strict\"; // Do stuff }; $(document).ready(function ()

Which is better:

var foo = 0,
    fnFoo = function (bar)
    {
        "use strict";
        // Do stuff
    };

$(document).ready(function ()
{
    "use strict";
    fnFoo(foo);
});

OR

$(document).ready(function ()
{
    "use strict";

    var foo = 0,
        fnFoo = function (bar)
        {
            "use strict";
            // Do stuff
        };

    fnFoo(foo);
});

The difference is th开发者_JAVA百科e location of the variable/function declarations. In this case, assume that only the ready event needs to use foo and fnFoo.


If only the ready event needs it, then put it in ready. That's the whole point of encapsulation. Restrict access to variables as much as possible to reduce bugs in code. What happens if you accidentally declare another foo or fnFoo by accident later on?

Not only that, but it makes your code more understandable. It means that you know exactly what each variable is used for and where.


Definitely use the latter case, so 1. the vars are grouped with the code that uses them, and 2. you aren't polluting the global scope with your vars.


You only need to wait for the document to be ready so that jQuery knows that the DOM is fully set up and thus can access form fields and other DOM objects. So, unless your function needs to access DOM elements, I'd declare page-wide vars and functions before the $(document).ready(... block, and, when you know they work move that code out into a separate script file, especially if that function is going to be reused in other parts of your web.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号