JavaScript:两个独立的脚本 - 共享变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8348401/
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
JavaScript: Two separate scripts - share variables?
提问by Bobby S
If I have two separate scripts in an HTML page with JavaScript are the variables shared between the entire page? Or only within their own declarations?
如果我在带有 JavaScript 的 HTML 页面中有两个单独的脚本,那么整个页面之间是否共享变量?还是只在他们自己的声明中?
Example:
例子:
<script> var title = "Hello World!"; </script>
// random HTML/PHP
<script> document.write(title); </script>
Will that write "Hello World!"? This seems like bad coding convention how else could I achieve something like this with proper form.
那会写“Hello World!”吗?这似乎是糟糕的编码约定,我怎么能以适当的形式实现这样的事情。
回答by dgvid
Variable title in your example is declared as a global variable, therefore it will be available to any and all scripts loaded into the same page. Whats more, if there is already a global variable named title
on the same page, its value will be overwritten when you assign it the value "Hello World!"
示例中的变量 title 被声明为全局变量,因此它可用于加载到同一页面的任何和所有脚本。更重要的是,如果title
在同一个页面上已经有一个全局变量,当你给它赋值“Hello World!”时,它的值会被覆盖。
The usual practice to avoid this sort of problem is to declare exactly one global variable, then put all of your other variables inside it. For example:
避免此类问题的通常做法是声明一个全局变量,然后将所有其他变量放入其中。例如:
var bobbyS_vars = {
title: "Hello World!";
};
Assign that lone global variable a name that no one else is likely to choose, such as your name or employer's name or best-of-all, a domain name that belongs you or your employer.
为这个唯一的全局变量指定一个其他人可能不会选择的名称,例如您的姓名或雇主的名称,或者最好是属于您或您的雇主的域名。
Another, more common way to handle this problem is to take advantage of of the way that JavaScript handles variable scope within functions. For example, create an anonymous function, declare allof your code inside that function, then call the function at the end of the declaration by putting () at the end of the declaration. For example:
另一种更常见的处理这个问题的方法是利用 JavaScript 在函数内处理变量作用域的方式。例如,创建一个匿名函数,在该函数内声明所有代码,然后通过在声明末尾放置 () 来调用声明末尾的函数。例如:
(function() {
var title = "Hello World!";
document.write(title);
})();
// title is not in scope here, so it is undefined,
// unless it were declared elsewhere.
If you wantto share some variables, but not others, have your anonymous function use a combination of approaches:
如果您想共享一些变量,而不是其他变量,请让您的匿名函数使用以下方法的组合:
var bobbyS_vars = {
title: "Hello World!";
};
(function() {
var employeeId = "E 298";
var count = 7;
document.write("<p>" + bobbyS_vars.title + "</p>");
document.write("<p>" + employeeId + "</p>");
})();
// At this point, bobbyS_vars.title is in scope and still has the
// value "Hello World!". Variables employeeId and count are not
// in scope and effectively private to the code above.
One final note. All of the functions that your code declares are also effectively global variables. So, if you create a function named printTitle, it is 1) available to all other code on the page and 2) could overwrite or be overwritten by another function on the same page also named printTitle. You can protect and/or expose your functions the same way you would any other variable:
最后一点。您的代码声明的所有函数也是有效的全局变量。因此,如果您创建一个名为 printTitle 的函数,它 1) 可用于页面上的所有其他代码,并且 2) 可以覆盖或被同一页面上另一个名为 printTitle 的函数覆盖。您可以像处理任何其他变量一样保护和/或公开您的函数:
var bobbyS_vars = { };
(function() {
// Private functions
var function = addOne(i) {
return i + 1;
};
// Public vars
bobbyS_vars.title: "Hello World!";
// Public functions
bobbyS_vars.printTitle = function() {
document.write("<p>" + bobbyS_vars.title + "</p>");
document.write("<p>" + addOne(41) + "</p>");
};
})();
// At this point, function addOne is not directly accessible,
// but printTitle is.
bobbyS_vars.printTitle();
Note that although function addOne is effectively a private function within the closure, it is still accessible indirectly, via the printTitle function because addOne and printTitle are both within the same scope.
请注意,虽然函数 addOne 实际上是闭包中的私有函数,但它仍然可以通过 printTitle 函数间接访问,因为 addOne 和 printTitle 都在同一范围内。
回答by gilly3
title
is in the Global
scope, which, in the case of JavaScript running in a web browser, is the window
object. When you say var title = "Hello World!"
outside of any function that would limit its scope, it is the same as saying window.title = "Hello World!"
.Your code is equivalent to this:
title
在Global
作用域中,对于在 Web 浏览器中运行的 JavaScript,它是window
对象。当你说var title = "Hello World!"
在任何会限制其范围的函数之外时,它与说相同。你的window.title = "Hello World!"
代码等价于:
<script>
window.title = "Hello World!";
</script>
<!-- random HTML/PHP -->
<script>
document.write(title);
// or document.write(window.title) works just as well
</script>
回答by Feisty Mango
They will all be "shared" in accordance with scoping rules and such. Separate files has no effect on this EXCEPT the order of the inclusion of said files.
它们都将根据范围规则等进行“共享”。除了包含所述文件的顺序外,单独的文件对此没有影响。
Edit: The same rule applies to inline scripts as well.
编辑:同样的规则也适用于内联脚本。
And to elaborate on the exception:
并详细说明异常:
If I have file Foo where I declare the following:
如果我在文件 Foo 中声明以下内容:
var fooVar = barVar;
var fooVar = barVar;
Then I have file Bar where I declare the following:
然后我有文件栏,我在其中声明以下内容:
var barVar = 'bar';
var barVar = 'bar';
And I include them in this order:
我按以下顺序包含它们:
<script type="javascript/text" src="foo.js"></script>
<script type="javascript/text" src="bar.js"></script>
You will get a interpreted error because the use of barVar
comes before its declaration.
你会得到一个解释错误,因为barVar
在它的声明之前使用了。
回答by Jonathan M
The window
holds all variables. All scripts are in the mother window
object. So all variables are in one space. They can, however, be localized to functions, etc.
将window
持有的所有变量。所有脚本都在母window
对象中。所以所有变量都在一个空间中。但是,它们可以本地化为函数等。
回答by Jemaclus
In this case, title would be a global variable. You need to encapsulate the variable within a scope. There are various methods for doing so. My preference is a self-executing anonymous function, which would be done like so:
在这种情况下,title 将是一个全局变量。您需要将变量封装在一个范围内。有多种方法可以这样做。我的偏好是一个自动执行的匿名函数,它会像这样完成:
(function() {
var title = "Hello world!";
alert(title); // would pop up "Hello World!" since title is in scope
});
alert(title); // title doesn't exist, because it's outside the scope