JavaScript global variables & self-invoking anonymous functions

后端 未结 4 2168
走了就别回头了
走了就别回头了 2021-02-15 16:24

So I\'ve been reading through Javascript - The Good Parts and one thing that Crockford points out is the use weakness of global variables in Javascript, in such a way that if yo

相关标签:
4条回答
  • 2021-02-15 17:08

    Making it a global function is not the answer. Why wouldn't you do this? This keeps x out of the global namespace.

    (function () {
        var x = 'meh';
        alert(typeof x);  //string
    })();
    
    0 讨论(0)
  • 2021-02-15 17:20

    To create applications with javascript, you must attempt to keep variables in a local scope, and anything inside a namespace. It's a good pratice and prevent a serie of harm codes and unespected behaviors.

    read this

    it's a article talking about the vantages of doing that.

    0 讨论(0)
  • 2021-02-15 17:26

    That's a perfectly legal way of doing things -- the variables inside of your function (as long as they are prefaced by var) are local to the function. It's called the module pattern, and it's very well accepted.

    0 讨论(0)
  • 2021-02-15 17:29
    (function (global) {
        global.x = 'meh';
    })(window);
    (function () {
        alert(typeof x); // string
    })();
    
    0 讨论(0)
提交回复
热议问题