javascript <script> 标签的全局范围是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17494247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:31:25  来源:igfitidea点击:

What is the global scope of <script> tag?

javascript

提问by curiousBoy

I had made flag and made my previous question deleted because of missunderstanding.

由于误解,我已经标记并删除了我之前的问题。

I'm working on a classic asp project.

我正在做一个经典的 asp 项目。

let's say you have so many <script></script>tags in your code.

假设您的<script></script>代码中有这么多标签。

For instance:

例如:

line 10: <script> ..function 1 definition here..</script>

第 10 行: <script> ..function 1 definition here..</script>

line 200: <script> .. function 2 definition here..</script>

第 200 行: <script> .. function 2 definition here..</script>

line 5000: <script> ..function 3 definition here..</script>

第 5000 行: <script> ..function 3 definition here..</script>

also at line 6000: I have another tag which is trying to call function1.

同样在第 6000 行:我有另一个标签试图调用 function1。

is that possible without using *.js file ?

这可能不使用 *.js 文件吗?

For instance:

例如:

line 6000:

第 6000 行:

<script> function1(); </script>

Those scripts are not defined in <head>tag.

这些脚本没有在<head>标签中定义。

I know its not useful but I need to know is there any way of it or not.

我知道它没有用,但我需要知道是否有任何方法。

Hope its more clear now!

希望现在更清楚了!

回答by Kevin Nacios

anything inside the script tags gets run immediately. if you define function a()in your first script element, then it will add a function called ato your global namespace. any javascript you execute later on in other script elements will have access to it.

脚本标签内的任何内容都会立即运行。如果您function a()在第一个脚本元素中定义,那么它将添加一个调用a到您的全局命名空间的函数。您稍后在其他脚本元素中执行的任何 javascript 都可以访问它。

<script type="text/javascript">
   function a() {
       alert('hi');
   }
</script>

...

<script type="text/javascript">
    a();
</script>

回答by Sumurai8

Yes, that is possible, assuming function1is in the global scope (e.g. not in a wrapper function/self-invoking function).

是的,这是可能的,假设function1在全局范围内(例如不在包装函数/自调用函数中)。

回答by Sumurai8

Of course it is possible . You just need to define it in global namespace. Hereis the link which should give you an idea and better understanding. It also includes very simple examples.

当然有可能。你只需要在全局命名空间中定义它。是应该给你一个想法和更好的理解的链接。它还包括非常简单的示例。