Global functions in javascript

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

提交回复
热议问题