2011-03-06 194 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) { 
相關問題