2011-03-06 111 views
1

我想创建一个可重用的javascript对象(我想用新的)。当我尝试新建一个自定义对象时,出现错误:如何在模块中创建JavaScript对象构造函数?

"org.myorg.sadp.section.sadpSection is not a constructor"

我将模块化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"); 

什么我错在这里做什么?

谢谢!

回答

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也是不必要的。

+0

也就是说删除'.section'从线'org.myorg.sadp.section =(函数(ns)'并且你被设置了。 – 2011-03-06 06:47:25

+0

错过了那个错字......感谢一堆! – Nick 2011-03-06 06:50:12

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

0

你的问题是该位的位置:

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

它应该是:

org.myorg.sadp = (function(ns) { 
相关问题