您的示例中的变量标题被声明为全局变量,因此它可用于加载到同一页面中的任何和所有脚本。更重要的是,如果同一页面上已经有一个名为title的全局变量,当你给它赋值“Hello World!”时,它的值会被覆盖
避免此类问题的通常做法是只声明一个全局变量,然后将所有其他变量放入其中。例如:
var bobbyS_vars = {
title: "Hello World!";
};
为这个唯一的全局变量分配一个其他人不可能选择的名称,例如您的姓名或雇主的名字,或者最重要的是,一个属于您或您的雇主的域名。
处理这个问题的另一种更常见的方法是利用 JavaScript 处理函数内变量范围的方式。例如,创建一个匿名函数,在该函数中声明所有代码,然后通过在声明末尾放置 () 在声明末尾调用该函数。例如:
(function() {
var title = "Hello World!";
document.write(title);
})();
// title is not in scope here, so it is undefined,
// unless it were declared elsewhere.
如果您想要共享一些变量,而不是其他变量,请让您的匿名函数使用多种方法:
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.
最后一点。您的代码声明的所有函数实际上也是全局变量。因此,如果您创建一个名为 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();
请注意,虽然 addOne 函数实际上是闭包中的私有函数,但它仍然可以通过 printTitle 函数间接访问,因为 addOne 和 printTitle 都在同一范围内。