简体   繁体   中英

Is it best practice to define global JavaScript objects in HTML?

I have a web project that has the following lines of code in it

<script>var obj = {...}</script>
<script src='./app.js'></script>

./app.js loaded by the second script tag uses obj defined by the first script tag. You could say that obj is a global variable to ./app.js .

I don't want to define obj inside ./app.js because it's a very large object but is this bad practice to define global variables like this?

You could avoid making obj global by passing it into app.js somehow.

<script src='./app.js'></script>
<script>
   someFunctionToInitAppJs( { 
     // ... 
   })
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM