Global functions in javascript

后端 未结 6 2213
攒了一身酷
攒了一身酷 2020-12-06 16:43

I\'m new to js and trying to understand global and private functions. I understand global and local variables. But if I have an html named test.html and a 2 js

6条回答
  •  猫巷女王i
    2020-12-06 16:58

    Anything defined in a file without any sort of wrapper will be bound to the window object. Anything bound to the window object is global.

    Example:

    //these are global variables
    foo = 123;
    var ABC = 'school';
    
    //these are "private" variables
    test = function(){
      var foo = 123
    }
    
    (function(){
      var ABC = 'school';
    }).call(this);
    

    Since global variables in every file will be part of the window object, you can access them between files. It is important when creating "private" variables you add var. This says override any global variables in the current "wrapper". If I have a global variable foo and I define it again in a function with var they will be separate.

    var foo = 123;
    (function(){
      var foo = 987; //this foo is separate from the above foo
    }).call(this);
    

    If you do have a "wrapper" and you want to define a global function you can do it like this:

    window.foo = 123;
    (function(){
      window.foo = 123;
    }).call(this);
    

    Both functions will do the same thing.

    Personally, I prefer to put everything in a wrapper and only define global variables when I need them using window.

    (function(){
    
      //all code goes here
    
      //define global variable
      window.foo = 123;
    
    })call(this);
    

提交回复
热议问题