Bob*_*y S 21 javascript coding-style
如果我在带有JavaScript的HTML页面中有两个单独的脚本,那么整个页面之间是否共享变量?或者仅在他们自己的声明中?
例:
<script> var title = "Hello World!"; </script>
// random HTML/PHP
<script> document.write(title); </script>
Run Code Online (Sandbox Code Playgroud)
那会写"Hello World!"吗?这似乎是错误的编码约定我怎么能用正确的形式实现这样的事情.
dgv*_*vid 28
示例中的变量标题被声明为全局变量,因此它将可用于加载到同一页面的任何和所有脚本.更重要的是,如果已经有一个title在同一页面上命名的全局变量,当您为其分配值"Hello World!"时,它的值将被覆盖.
避免此类问题的通常做法是声明一个全局变量,然后将所有其他变量放入其中.例如:
var bobbyS_vars = {
title: "Hello World!";
};
Run Code Online (Sandbox Code Playgroud)
为这个单独的全局变量分配一个其他人无法选择的名称,例如您的姓名或雇主的名字,或者最重要的是,属于您或您的雇主的域名.
处理此问题的另一种更常见的方法是利用JavaScript处理函数内的变量范围的方式.例如,创建一个匿名函数,在该函数内声明所有代码,然后通过put()在声明的末尾调用声明末尾的函数.例如:
(function() {
var title = "Hello World!";
document.write(title);
})();
// title is not in scope here, so it is undefined,
// unless it were declared elsewhere.
Run Code Online (Sandbox Code Playgroud)
如果您想共享一些变量而不是其他变量,请让您的匿名函数使用多种方法:
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_var.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.
Run Code Online (Sandbox Code Playgroud)
最后一点说明.您的代码声明的所有函数也是有效的全局变量.因此,如果您创建一个名为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();
Run Code Online (Sandbox Code Playgroud)
请注意,尽管函数addOne实际上是闭包内的私有函数,但它仍然可以通过printTitle函数间接访问,因为addOne和printTitle都在同一范围内.
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>
Run Code Online (Sandbox Code Playgroud)
它们都将根据范围规则等进行“共享”。除了包含所述文件的顺序之外,单独的文件对此没有影响。
编辑:相同的规则也适用于内联脚本。
并详细说明异常:
如果我有文件 Foo,其中我声明以下内容:
var fooVar = barVar;
然后我有文件 Bar,其中声明以下内容:
var barVar = 'bar';
我按以下顺序将它们包括在内:
<script type="javascript/text" src="foo.js"></script>
<script type="javascript/text" src="bar.js"></script>
Run Code Online (Sandbox Code Playgroud)
您将得到一个解释错误,因为使用barVar位于其声明之前。