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

后端 未结 5 1802
梦毁少年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:44

    In global scope there is no semantic difference.

    But you really should avoid a=0 since your setting a value to an undeclared variable.

    Also use closures to avoid editing global scope at all

    (function() {
       // do stuff locally
    
       // Hoist something to global scope
       window.someGlobal = someLocal
    }());
    

    Always use closures and always hoist to global scope when its absolutely neccesary. You should be using asynchronous event handling for most of your communication anyway.

    As @AvianMoncellor mentioned there is an IE bug with var a = foo only declaring a global for file scope. This is an issue with IE's notorious broken interpreter. This bug does sound familiar so it's probably true.

    So stick to window.globalName = someLocalpointer

提交回复
热议问题