Global functions in javascript

后端 未结 6 2217
攒了一身酷
攒了一身酷 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: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

    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.

提交回复
热议问题