如何在模块中创建JavaScript对象构造函数?

时间:2011-03-06 06:35:25

标签: javascript

我正在尝试创建一个可重用的javascript对象(我想使用new)。当我尝试新建一个自定义对象时,出现错误:

  

“org.myorg.sadp.section.sadpSection不是构造函数”

我因为命名空间原因而模块化我的JS。我想知道这是不是问题:

if (!window.org) var org = { myorg: {} };    
if (!org.myorg) org["myorg"] = { sadp: {} };
if (!org.myorg.sadp) org.myorg["sadp"] = {};

org.myorg.sadp.section = (function(ns) {
    if (ns.section) {
        return ns;
    }
    else {
        ns.section = {};
    }
    ns.section.sadpSection = function(name) {
        this.name = name;
        this.isCompleted = false;
        this.booleanQuestions = new Array();
        this.multipleChoiceQuestions = new Array();
        this.sliders = new Array();
        return true;
    }
    return ns;

} (org.myorg.sadp))

这会导致错误:

var myObj = new  org.myorg.sadp.section.sadpSection("test");

我在这里做错了什么?

谢谢!

3 个答案:

答案 0 :(得分:2)

您基本上使org.myorg.sadp.section等于org.myorg.sadp。这不是你想要的,它基本上是无限递归:

org.myorg.sadp.section == org.myorg.sadp.section.section

无论添加多少.section,情况都是如此。您可以将其更改为:

org.myorg.sadp.section = 
{
    sadpSection: function(name)
    {
        this.name = name;
        this.isCompleted = false;
        this.booleanQuestions = new Array();
        this.multipleChoiceQuestions = new Array();
        this.sliders = new Array();
    }
}

您可以添加:

if(!org.myorg.sadp.section.sadpSection)

避免重新分配构造函数。

这不是模块化的。返回true也是不必要的。

答案 1 :(得分:0)

我最近编写了一个namespace library来处理您可能想要查看的此类模块系统。我的想法是你会像这样使用它:

ns('org.myorg.sadp.section');

org.myorg.sadp.section.load('sadpSection', function(name) {
    this.name = name;
    this.isCompleted = false;
    // always better to use array literals than constructor
    this.booleanQuestions = []; 
    this.multipleChoiceQuestions = [];
    this.sliders = [];
    return true;
});

但基本上您遇到的问题是您要返回ns而不是section

答案 2 :(得分:0)

这就是问题所在:

org.myorg.sadp.section = (function(ns) {

应该是:

org.myorg.sadp = (function(ns) {