Declare multiple variables in JavaScript

后端 未结 5 1948
[愿得一人]
[愿得一人] 2021-02-06 21:18

I want to declare multiple variables in a function:

function foo() {
    var src_arr     = new Array();
    var caption_arr = new Array();
    var fav_arr     =          


        
5条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-06 22:02

    Please stay away from that assignment pattern, even if you wanted to have all variables pointing to the same object.

    In fact, only the first one will be a variable declaration, the rest are just assignments to possibly undeclared identifiers!

    Assigning a value to an undeclared identifier (aka undeclared assignment) is strongly discouraged because, if the identifier is not found on the scope chain, a GLOBAL variable will be created. For example:

    function test() {
        // We intend these to be local variables of 'test'.
        var foo = bar = baz = xxx = 5;
        typeof foo; // "number", while inside 'test'.
    }
    test();
    
    // Testing in the global scope. test's variables no longer exist.
    typeof foo; // "undefined", As desired, but,
    typeof bar; // "number", BAD!, leaked to the global scope.
    typeof baz; // "number"
    typeof xxx; // "number"
    

    Moreover, the ECMAScript 5th Strict Mode, disallows this kind of assignments. Under strict mode an assignment made to a non-declared identifier will cause a TypeError exception, to prevent implied globals.

    By contrast, here is what we see if written correctly:

    function test() {
        // We correctly declare these to be local variables inside 'test'.
        var foo, bar, baz, xxx;
        foo = bar = baz = xxx = 5;
    }
    test();
    
    // Testing in the global scope. test's variables no longer exist.
    typeof foo; // "undefined"
    typeof bar; // "undefined"
    typeof baz; // "undefined"
    typeof xxx; // "undefined"
    

提交回复
热议问题