2012-09-17 39 views
-1

我正在学习JavaScript,其范围,名称空间和全局变量(以及如何不使用它们)。为什么这些变量不在全球范围内?

我有一个完整的例子,说明我的问题。我构建了一个名为“JavascriptLearning”的名称空间,然后将一个Customer函数添加到名称空间。它按预期工作,将JavascriptLearning对象/名称空间添加到全局对象,并将Customer函数添加到此名称空间。

之后,我创建了四个变量。 我为什么这四个变量APPNAME测试cust1notNewInstance没有被添加到全球范围,因为我认为他们会感到困惑。

(我发现,他们并没有受到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> 
+0

werks4me,我在Chrome 21中获得了“Matt Company”。 – ken

+0

@ken脚本运行成功,我问为什么我没有在全局范围内看到我的一些变量 – contactmatt

+1

我看到全局范围内的变量Chrome调试器...你确定你看到你认为你在看什么吗? –

回答

0

JavaScript没有正确的命名空间。当术语namespace与JavaScript一起使用时被错误地使用以引用分配给变量引用的范围。这时JavaScript只有函数范围,尽管在不久的将来它也会有块范围。

您可以通过将单个全局变量分配给对象字面量或函数来避免污染全局范围。对象字面值内的所有东西都将是一个属性,其中函数内的任何内容都需要使用var关键字进行限定。在顶层函数中,使用"use strict";编译指示来检查未声明的引用,否则这些引用将隐含(意外)全局变量。

0

我在全局命名空间中看到了这些变量。你可能会误解?

我可以为你的学习贡献一些有用的东西,当声明变量时,你应该在当前函数的顶部声明它们。这在解释时自动发生,被称为variable hoisting

这是显而易见的,例如,当你在你宣布关闭添加提醒,

(function(nameSpace) { 
    nameSpace.Customer = function Customer(name, company) { 
    this.name = name; 
    this.company = company; 
    alert(appName); 

    return 0; 
    } 
})(JavascriptLearning); 

程序上阅读的代码,你会认为是未定义,但是发生了什么事是这样的,

var JavascriptLearning = window.JavascriptLearning || {}; 
var var appName, test, cust1, notNewInstance; 

然后封闭获得对函数生命期的其余部分的所有变量的引用。

相关问题