do included javascript files have access to global variables in the parent document?

三世轮回 提交于 2019-12-10 18:48:46

问题


Imagine some code something like this:

  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
     "http://www.w3.org/TR/html4/loose.dtd">
  <HTML>
  <HEAD>
  <TITLE>BLAH</TITLE>
  <script language='Javascript' type='text/javascript'>
  var ScriptVersionReqd='1.0';
  </script>

  <script language='JavaScript' type='text/javascript' src='clientscript.js'></script>
  etc. etc.

Does clientscript.js have access to the variable "ScriptVersionReqd"? If not, why not?


回答1:


Yes.

As long as the global variable has been put into global scope before it is called by the external script.

Edit in response to a comment: See here for a good explanation of javascript variable scope.




回答2:


Yes. You can see examples of this in things like Google Adsense. With Adsense, you first start by defining the width, colors, etc. Then you include the script which looks for those variables, and determines the output based upon those values.

<script type="text/javascript"><!--
  google_ad_client = "pub-42235573";
  google_ad_slot = "0774868545";
  google_ad_width = 728;
  google_ad_height = 90;
  //-->
</script>
<script type="text/javascript" 
        src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>



回答3:


Yes, there is no difference for the scope whether the script is included from a file or inline in the script tag.



来源:https://stackoverflow.com/questions/1322341/do-included-javascript-files-have-access-to-global-variables-in-the-parent-docum

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!