【问题标题】:JavaScript Namespace Uncaught Type ErrorJavaScript 命名空间未捕获类型错误
【发布时间】:2011-11-15 05:28:10
【问题描述】:

我一直在尝试通过为我的代码创建一个命名空间来使我的 javascript 代码更好,这样就不会出现全局变量/函数冲突,并且还将命名空间中的所有内容都放在匿名函数中,因此除非另有明确说明,否则所有内容都是私有的通过return语句。
Atm,我收到“未捕获的类型错误:对象不是函数”

var Namespace = (function() {
    //private variables/functions
    var a;
    var b;
    function priv_func1() {
        //do stuff
    }

    //public variables/functions
    return {
        pub_var1: b,
        pub_func1: function() {
            //do stuff
        }
    };
})();

$(document).ready(function() {
    var myName = new Namespace();
    myName.pub_func1();
}

因此,当我删除命名空间定义末尾的 () 将函数声明转换为函数表达式时,我没有收到任何错误,但在示例中我看到它们在那里有 (),所以我我想知道发生了什么事。

我也将它放在命名空间定义的开头,以便在用户不小心忽略新关键字时进行更正。

if (!(this instanceof Namespace))
        return new Namespace();

编辑:另外,我应该将我的文档就绪函数放在命名空间定义之前还是之后。

【问题讨论】:

    标签: javascript object namespaces closures global


    【解决方案1】:

    有效!您不必使用 new,因为您尚未定义 constructor

    $(document).ready(function() {
       Namespace.pub_func1();
    });
    

    您尝试做的事情是通过 modules 创建构造函数完成的。 让我给你看一个 Javascript: Design Patterns

    的例子

    创建构造函数的模块

    [..] 但有时它是 使用构造函数创建对象更方便。你仍然可以做 使用模块模式。唯一的区别是立即函数 包装模块将在最后返回一个函数,而不是一个对象。

    考虑以下创建构造函数的模块模式示例

    MYAPP.utilities.Array:
    MYAPP.namespace('MYAPP.utilities.Array');
    MYAPP.utilities.Array = (function () {
       // dependencies
       var uobj = MYAPP.utilities.object,
       ulang = MYAPP.utilities.lang,
       // private properties and methods...
       Constr;
       // end var
       // optionally one-time init procedures
       // ...
       // public API -- constructor
       Constr = function (o) {
          this.elements = this.toArray(o);
       };
       // public API -- prototype
       Constr.prototype = {
          constructor: MYAPP.utilities.Array,
          version: "2.0",
          toArray: function (obj) {
             for (var i = 0, a = [], len = obj.length; i < len; i += 1) {
                a[i] = obj[i];
             }
             return a;
          }
       };
       // return the constructor 
       // to be assigned to the new namespace
       return Constr;
    }());
    
    The way to use this new constructor will be like so:
    var arr = new MYAPP.utilities.Array(obj);
    

    【讨论】:

    • 是的,我现在明白了。这 ();在命名空间的末尾意味着您不必定义对象并将其分配给命名空间。您可以直接使用命名空间。
    • @Michael:如果你想使用构造函数,你必须实现一个命名空间来创建构造函数。
    猜你喜欢
    • 2020-09-04
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    • 2013-11-11
    • 2013-12-03
    相关资源
    最近更新 更多