简体   繁体   中英

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.

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();
// -----------------------------^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM