如何知道来自不同...“命名空间”的变量?
如何从外部 javascript 文件中访问在另一个地方声明的某个变量?
假设在 html 文件中我有以下内容
<head>
<script>
var a = 'something';
</script>
<head>
<body>
<iframe src="otherfile.html"/>
</body>
,在 otherfile.html 部分中,我有
alert(a);
如何确保收到一条警告消息说“某事”?
我认为 Google Adsense 就是这样做的,他们的代码是:
<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>
http://pagead2.googlesyndicate 中的脚本如何.com/pagead/show_ads.js知道这些变量(例如google_ad_client)吗?
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) ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
没关系。
页面中的所有
块共享相同的上下文和变量。
It doesn't matter.
All
<script>
blocks in the page share the same context and variables.当一个变量定义时没有
var
时,它被认为存在于全局范围内。当你的 JS 加载到页面中时,它会知道当时全局存在的任何变量。所以,谷歌正在做的是定义一些变量,然后加载到外部脚本中。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.该脚本可以假设这些变量将被设置。他们一定是因为他们被需要。该脚本可以检查它们是否未定义,并在未定义时优雅地失败(不执行任何操作)。这些变量不在另一个命名空间中。
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.