Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript "Object not a constructor" error when using namespaces?

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?

like image 600
Polaris878 Avatar asked May 02 '26 15:05

Polaris878


1 Answers

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
like image 145
bcherry Avatar answered May 04 '26 04:05

bcherry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!