Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
845 views
in Technique[技术] by (71.8m points)

scope - Global variables in Javascript across multiple files

A bunch of my JavaScript code is in an external file called helpers.js. Inside the HTML that calls this JavaScript code I find myself in need of knowing if a certain function from helpers.js has been called.

I have attempted to create a global variable by defining:

var myFunctionTag = true;

In global scope both in my HTML code and in helpers.js.

Heres what my html code looks like:

<html>
...
<script type='text/javascript' src='js/helpers.js'></script>    
...
<script>
  var myFunctionTag = false;
  ...
  //I try to use myFunctionTag here but it is always false, even though it has been se t to 'true' in helpers.js
</script>

Is what I am trying to do even feasible?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to declare the variable before you include the helpers.js file. Simply create a script tag above the include for helpers.js and define it there.

<script type='text/javascript' > 
  var myFunctionTag = false; 
</script>
<script type='text/javascript' src='js/helpers.js'></script>     
... 
<script type='text/javascript' > 
  // rest of your code, which may depend on helpers.js
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...