Javascript “Not a Constructor” Exception while creating objects

后端 未结 14 1135
[愿得一人]
[愿得一人] 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:35

    I just want to add that if the constructor is called from a different file, then something as simple as forgetting to export the constructor with

    module.exports = NAME_OF_CONSTRUCTOR
    

    will also cause the "Not a constructor" exception.

    0 讨论(0)
  • 2020-11-27 18:43

    The code as posted in the question cannot generate that error, because Project is not a user-defined function / valid constructor.

    function x(a,b,c){}
    new x(1,2,3);               // produces no errors
    

    You've probably done something like this:

    function Project(a,b,c) {}
    Project = {};               // or possibly   Project = new Project
    new Project(1,2,3);         // -> TypeError: Project is not a constructor
    

    Variable declarations using var are hoisted and thus always evaluated before the rest of the code. So, this can also be causing issues:

    function Project(){}
    function localTest() {
        new Project(1,2,3); // `Project` points to the local variable,
                            // not the global constructor!
    
       //...some noise, causing you to forget that the `Project` constructor was used
        var Project = 1;    // Evaluated first
    }
    
    0 讨论(0)
  • 2020-11-27 18:43

    For me it was the differences between import and require on ES6.

    E.g.

    // processor.js
    class Processor {
    
    }
    
    export default Processor
    
    //index.js
    const Processor = require('./processor');
    const processor = new Processor() //fails with the error
    
    import Processor from './processor'
    const processor = new Processor() // succeeds
    
    0 讨论(0)
  • 2020-11-27 18:44

    To add to @wprl's answer, the ES6 object method shorthand, like the arrow functions, cannot be used as a constructor either.

    0 讨论(0)
  • 2020-11-27 18:45

    An additional cause of this can be ES2015 arrow functions. They cannot be used as constructors.

    const f = () => {};
    new f(); // This throws "f is not a constructor"
    
    0 讨论(0)
  • 2020-11-27 18:45

    I have a class in one file that I'm importing into a test file:

    //Vec.js
    class Vec {
    
    }
    
    module.exports.Vec = Vec;
    

    Changing

    //Vec.test.js
    const Vec = require('./Vec');
    const myVec = new Vec(); //TypeError: Vec is not a constructor
    

    to

    //Vec.test.js
    const {Vec} = require('./Vec');
    const myVec = new Vec(); //Succeeds!
    

    resolved this error for me.

    0 讨论(0)
提交回复
热议问题