Difference between variable declaration syntaxes in Javascript (including global variables)?

后端 未结 5 1792
梦毁少年i
梦毁少年i 2020-11-22 01:40

Is there any difference between declaring a variable:

var a=0; //1

...this way:

a=0; //2

...or:



        
5条回答
  •  被撕碎了的回忆
    2020-11-22 02:31

    Bassed on the excellent answer of T.J. Crowder: (Off-topic: Avoid cluttering window)

    This is an example of his idea:

    Html

    
    
      
        
        
        
      
    
      
        

    Hello !

    init.js (Based on this answer)

    var MYLIBRARY = MYLIBRARY || (function(){
        var _args = {}; // private
    
        return {
            init : function(Args) {
                _args = Args;
                // some other initialising
            },
            helloWorld : function(i) {
                return _args[i];
            }
        };
    }());
    

    script.js

    // Here you can use the values defined in the html as if it were a global variable
    var a = "Hello World " + MYLIBRARY.helloWorld(2);
    
    alert(a);
    

    Here's the plnkr. Hope it help !

提交回复
热议问题