How to know variables from different…“namespaces”?

落花浮王杯 提交于 2019-12-04 07:16:26

问题


How can I reach some variable declared in another place from within an external javascript file ?

Suppose in an html file I have the following

<head>
 <script>
   var a = 'something';
 </script>
<head>
<body>
<iframe src="otherfile.html"/>
</body>

and inside otherfile.html, in the section, I have

alert(a);

How can I make sure I get an alert message saying "something" ?

I think Google Adsense does this, their code is:

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

How can the script in http://pagead2.googlesyndication.com/pagead/show_ads.js know those variables (e.g. google_ad_client) ?


回答1:


when a variable is defined without var it is said to exist in global scope. When your JS is loaded into your page, it is aware of any variables that exist globally at that time. So, what google is doing is defining some variables and then loading in an external script.




回答2:


It doesn't matter.

All <script> blocks in the page share the same context and variables.




回答3:


The script can just assume that those variables will be set. They must be because they are needed. The script can check if they are undefined and fail gracefully (do nothing) when they are not. The variables are not in another namespace.



来源:https://stackoverflow.com/questions/6024748/how-to-know-variables-from-different-namespaces

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