我正在学习JavaScript,其范围,名称空间和全局变量(以及如何不使用它们)。为什么这些变量不在全球范围内?
我有一个完整的例子,说明我的问题。我构建了一个名为“JavascriptLearning”的名称空间,然后将一个Customer函数添加到名称空间。它按预期工作,将JavascriptLearning对象/名称空间添加到全局对象,并将Customer函数添加到此名称空间。
之后,我创建了四个变量。 我为什么这四个变量APPNAME,测试,cust1和notNewInstance没有被添加到全球范围,因为我认为他们会感到困惑。
(我发现,他们并没有受到Chrome的调试,并在随后结束执行观看“这个”对象,在警告呼叫加入到全局命名空间。)
<html>
<head>
<script>
var JavascriptLearning = window.JavascriptLearning || {};
// Pass in the namespace
(function(nameSpace) {
// Uppercased because we are using this function as a "class".
nameSpace.Customer = function Customer(name, company) {
// Using this, we create a new object and add properties to it. Puts an object dynamically with a "shape"
this.name = name;
this.company = company;
// Without a return keyword, the return value would be undefined
return 0;
}
})(JavascriptLearning);
var appName = "Hello";
var test = function TEST() { return; }
// Assigning the new keyword is used to return an object as defined in the function.
var cust1 = new JavascriptLearning.Customer("Matt", "Company");
// Not using the new keyword simply uses the return value of the function
var notNewInstance = JavascriptLearning.Customer("Test", "Company");
this.alert(cust1.name + " " + cust1.company);
</script>
</head>
<body>
</body>
</html>
werks4me,我在Chrome 21中获得了“Matt Company”。 – ken
@ken脚本运行成功,我问为什么我没有在全局范围内看到我的一些变量 – contactmatt
我看到全局范围内的变量Chrome调试器...你确定你看到你认为你在看什么吗? –