Anshul
Anshul

Reputation: 75

Javascript: Uncaught TypeError, not a constructor

I went though all the posts here related to this topic, but couldn't find a working solution. May be something very different in my code.

File 1, RequestFactory.js

function requestFactory() {
    this.createRequest = function (reportId) {
      var request;
      request = new xyzRequestManager.XyzRequest();
      return request;
    } 
    return {
      RequestFactory: requestFactory
    } 
 }

File 2,request.js

function loadData() {
  var request = requestFactory.createRequest(id);
  request.loadReport(report);
}

File 3, xyzRequestManager.js

function () {
 var xyzRequest = function() {
   this.loadReport = function(report) { --some data--}
 }
 return {
   XyzRequest: xyzRequest
 }
}

So the call starts from file2, i create the request object by calling requestFactory. There are bunch of other functions written in file 3, which gets called from file 1 in similar fashion, request factory object, and make call to the function.

This gives error as,

Uncaught TypeError: xyzRequestManager.XyzRequest is not a constructor

I have wasted hours on this, and still no clue what or where am I wrong. Any help would be appreciated.

Upvotes: 0

Views: 4066

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074148

You're returning an object with a property called XyzRequest, not xyzRequest, see the *** comment:

// Note: This is verbatim from the question other than this comment and
// the *** comment below.. It's not valid syntax on its own (the function
// would need a name), but I assume it's an excerpt from something larger.
function () {
 var xyzRequest = function() {
   this.loadReport = function(report) { --some data--}
 }
 return {
   XyzRequest: xyzRequest     // ***
 }
}

So to use it, you need that capital X:

request = new xyzRequestManager.XyzRequest();
// -----------------------------^

Upvotes: 1

Related Questions