1

I have created a "Namespace" of sorts using nested objects in Javascript and am trying to "new' up an instance of a javascript object.

//
// Create the ABC.DTO "namespace"
if (typeof (ABC) == 'undefined') var ABC= { DTO: {} };
//
// Define the ListType object
ABC.DTO.ListType = function (pId, pName) {

    var id   = pId;
    var name = pName;

    return {
        Id: id,
        Name: name
    }
};
//
// Create an instance of the "listType" object
var type1 = new ABC.DTO.ListType(1, 'Letter Type'); // THROWS ERROR

The error being thrown is "Object doesn't support this action" ... I have reviewed the following posts and, unless I am missing something I feel like the code is conformign correctly. Am I overlooking something?

Define a “nested” object constructor in JavaScript?

Instancing new objects in javascript

Community
  • 1
  • 1
Gary O. Stenstrom
  • 2,284
  • 9
  • 38
  • 59

1 Answers1

0

This works in the most simple case:

baz = { foo: {} };
baz.foo.bar = Function;
bop = new baz.foo.bar();

console.log(bop);

And the slightly more complex case:

var baz = { foo: {} };
baz.foo.bar = function(){};
var bop = new baz.foo.bar();

console.log(bop);

But fails in the aforementioned case due to hoisting.

References

Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265