1

I am trying to create a reusable javascript object (I want to use new). When I attempt to new up one of my custom objects I get an error:

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

I am modularizing my JS for namespace reasons. I wonder if that is the problem:

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))

This results in the error:

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

What am I doing wrong here?

Thanks!

3 Answers 3

2

You're basically making org.myorg.sadp.section equal org.myorg.sadp. This isn't want you want, and it's basically infinite recursion:

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

and the same is true no matter how many .sections you add. You can change it to:

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();
    }
}

You can add a:

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

to avoid reassigning the constructor.

That isn't any less modular. The return true is also unnecessary.

Sign up to request clarification or add additional context in comments.

1 Comment

That is to say remove .section from the line org.myorg.sadp.section = (function(ns) and you're set.
0

I recently wrote a namespace library for handling this type of module system you may want to check out. The idea is that you would use it like this:

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;
});

but basically the problem you are dealing with is that you are returning ns instead of section.

Comments

0

Your problem is this bit here:

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

It should be:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.