Redeclaring a javascript variable

后端 未结 8 1754
耶瑟儿~
耶瑟儿~ 2020-11-29 05:33

In this tutorial there is written:

If you redeclare a JavaScript variable, it will not lose its value.

Why should I redeclare a variable? Is it

相关标签:
8条回答
  • 2020-11-29 06:29

    An example of redeclaring a variable can be found in Google Analytics. When the JavaScript tracking code is initiated by the Google Analytics script, it declares or redeclares _gaq in this way:

    var _gaq = _gaq || [];
    

    In other words, if _gaq is already defined, _gaq is "redeclared" as itself. If it is not defined, it will be declared for the first time as an empty array.

    This allows the Google Analytics tracking code to support other scripts which may need to use the variable before Google Analytics code has initiated. As @xralf pointed out, JavaScript allows for this.

    Redeclaring a variable is useful in situations where it cannot be known if the variable has already been defined.

    By redeclaring a variable conditionally, as Google Analytics tracking code does, it allows for a variable to safely originate from more than one place.

    In this example it could be safe for other code using the _gaq variable to likewise check for a predefined _gaq variable. If it exists, it knows it can use it. If it doesn't exist, it knows that it should define it before trying to use it.

    0 讨论(0)
  • 2020-11-29 06:32

    Why should I redeclare a variable?

    You shouldn't. It makes for confusing code.

    Is it practical in some situations?

    No.

    0 讨论(0)
提交回复
热议问题