【问题标题】:Namespaced External Javascript inaccessible from target javascript目标 javascript 无法访问命名空间的外部 Javascript
【发布时间】:2012-01-19 02:15:05
【问题描述】:

我有我的 javascript 文件:

foo.js

var FooNS = {
   T:5,
   S: FooNS.T+5, //ERROR1
   doSomething : function(adder)
   {
     //Do Something here.
   }
};

这是我的另一个 js 文件:

useFoo.js

$(document).ready(function()
{
    FooNS.doSomething(5); //ERROR2
});

这是我在包含 js 的页面上看到的两个 Javascript 错误(通过 Chrome Inspector):

  • ERROR1 -> Uncaught TypeError: Cannot read property 'T' of undefined (foo.js)
  • ERROR2 -> Uncaught TypeError: Cannot call method 'doSomething' of undefined (in useFoo.js)

我无法弄清楚这些错误的原因/命名空间的正确用法。有什么建议吗?

【问题讨论】:

    标签: javascript jquery namespaces external undefined


    【解决方案1】:

    ERROR1 的原因:

    您正在尝试访问尚未完全实例化的对象的属性。只有在浏览器(解释器)执行脚本中的第 8 行(即};)后,FooNS 的创建才完成。

    为了初始化属性,最好使用 init 成员函数之类的,然后调用 FooNS 的定义,如下所示:

    var FooNS = {
       T: 5,
       S: 0,
       init: function() {
          this.S = this.T + 5; // this does not get executed till we call init(), so no error here
       },
       ...
    }; // <- creation of FooNS object is complete
    FooNS.init();
    

    ERROR2 的原因:

    浏览器在第一个错误 (ERROR1) 处停止,并且在该执行线程中不再执行任何 JS。因此,FooNS 对象没有正确创建,导致调用FooNS.doSomething(5)时出错

    【讨论】:

      【解决方案2】:

      T 不作为全局变量存在,这是您尝试使用它的方式。

      var FooNS = {
         T:5,
         S: T+5, // <-- here you are trying to access the global variable T
         doSomething : function(adder)
         {
           //Do Something here.
         }
      };
      

      您正在寻找的可能与此类似:

      var FooNS = {
         T:5,
         doSomething : function(adder)
         {
           //Do Something here.
         }
      };
      
      FooNS.S = FooNS.T+5;
      

      第二个错误是因为FooNS 由于第一个错误而从未创建为对象,因此FooNS 未定义。

      【讨论】:

      • 抱歉,在 SO 中输入问题时错过了这一点。我已经更新了我的问题。
      • 是的,就是这样。谢谢。
      猜你喜欢
      • 2020-05-05
      • 2015-01-14
      • 2012-09-04
      • 2016-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-11
      • 1970-01-01
      相关资源
      最近更新 更多