Javascript “Not a Constructor” Exception while creating objects

后端 未结 14 1218
[愿得一人]
[愿得一人] 2020-11-27 18:15

I am defining an object like this:

function Project(Attributes, ProjectWidth, ProjectHeight)
{
    this.ProjectHeight = ProjectHeight;
    this.ProjectWidth          


        
14条回答
  •  暖寄归人
    2020-11-27 18:48

    For my project, the problem turned out to be a circular reference created by the require() calls:

    y.js:
    var x = require("./x.js");
    var y = function() { console.log("result is " + x(); }
    module.exports = y;
    
    x.js:
    var y = require("./y.js");
    var my_y = new y(); // <- TypeError: y is not a constructor
    var x = function() { console.log("result is " + my_y; }
    module.exports = x;
    

    The reason is that when it is attempting to initialize y, it creates a temporary "y" object (not class, object!) in the dependency system that is somehow not yet a constructor. Then, when x.js is finished being defined, it can continue making y a constructor. Only, x.js has an error in it where it tries to use the non-constructor y.

提交回复
热议问题