2

I have the following JS code:

window.Foo = {};
window.Foo.Name1 = function()
{
    function Bar1(param1)
    {
        this.Name = param1;

    }

}


var gMyBar = new Foo.Name1.Bar1("hello world");
alert(gMyBar.Name);

I'm getting the error "Foo.Name1.Bar1 is not a constructor" in my Firefox error console... what gives?

2 Answers 2

8

You're confused about "namespaces" in JavaScript. JavaScript does not have namespaces, only objects and functions. You've declared Bar1 as a local function within the closure of the function Name1. It is not a member of Name. I'm not sure what you're going for here, but I think this is it:

var Foo = {
  Name1: {
    Bar1: function(param1) {
      this.Name = param1;
    }
  }
};

var gMyBar = new Foo.Name1.Bar1("hello world");
alert(gMyBar.Name); // hello world
Sign up to request clarification or add additional context in comments.

1 Comment

yep that idea is what im going for
3

The problem is that Bar1 is a local function, available only to the scope of the Name1 function.

If you want to access Bar1, you could make Name1 another namespace level:

window.Foo = {};
window.Foo.Name1 = {
  Bar1: function (param1) {
    this.Name = param1;
  }
};

var gMyBar = new Foo.Name1.Bar1("hello world");
alert(gMyBar.Name); // "hello world"

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.