Global functions in javascript

后端 未结 6 2147
攒了一身酷
攒了一身酷 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条回答
  • 2020-12-06 16:54

    in test2.js you can write this to make the function global

    window.abc = function(){...}
    

    and then in test1.js yo can access it like this

    window.parent.abc();
    

    I hope it will help you

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-12-06 16:58

    A modern approach (2020) to using global data is by using a global object literal and define there all your needed logic.

    const Website = {
      foo () {
        console.log('foo')
      },
      
      bar () {
        console.log('bar')
      }
    }
    
    document.addEventListener('DOMContentLoaded', () => {
      Website.foo()
      Website.bar()
    })

    If your code is more complex than a couple of lines you will need to separate your code into multiple files and with webpack you merge them together into one file.

    import Foo from './js/Foo.js'
    import Bar from './js/Bar.js'
    
    // define here another object literal or setup document events.
    // webpack will merge all this together into one file
    <script src="js/webpack-merged.js"></script>

    The reasons you don't want to import individual js files with html is described here. The jist of it is you will have poor performance, so you must bundle all your js.

    0 讨论(0)
  • 2020-12-06 17:02

    If you don't understand why global variables are bad, then why are you trying to avoid them?

    Global functions aren't necessarily bad. What's bad is state that anyone and anything and change.

    In general since you're new to Javascript, it's fine to start out with global functions spread out across multiple javascript files that you include in your html file via script tags.

    As you transition from beginner to intermediate, you will have to look into some "module" solution (I personally recommend RequireJS).

    For now though, you can make do with a simpler module pattern:

    var T1 = function() {
       return < some module object >
    })(); // notice the parenthesis
    

    Google "Javascript module pattern".

    Also see this answer.

    0 讨论(0)
  • 2020-12-06 17:03
    var SomeName = function() {
    
        var function1 = function (number) {
            return number+1;
        }
    
        var anotherFunction = function (number) {
            return number+2;
        }
    
        return {
            function1: function (number) {
                return function1(number);
            },
            function2: function (number) {
                return anotherFunction(number);
            }
        }
    }();
    

    calling

    console.log(SomeName.function1(1)); //logs 2

    console.log(SomeName.function2(1)); //logs 3

    0 讨论(0)
  • 2020-12-06 17:09

    Everything in JS is bound to containing scope. Therefore, if you define a function directly in file, it will be bound to window object, i.e. it will be global.

    To make it "private", you have to create an object, which will contain these functions. You are correct that littering global scope is bad, but you have to put something in global scope to be able to access it, JS libraries do the same and there is no other workaround. But think about what you put in global scope, a single object should be more than enough for your "library".

    Example:

    MyObject = {
        abc: function(...) {...},
        pqr: function(...) {...}
        // other functions...
    }
    

    To call abc for somewhere, be it same file or another file:

    MyObject.abc(...);
    
    0 讨论(0)
提交回复
热议问题