Javascript “Not a Constructor” Exception while creating objects

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

    I had a similar error and my problem was that the name and case of the variable name and constructor name were identical, which doesn't work since javascript interprets the intended constructor as the newly created variable.

    In other words:

    function project(name){
        this.name = name;
    }
    
    //elsewhere...
    
    //this is no good! name/case are identical so javascript barfs. 
    let project = new project('My Project');
    

    Simply changing case or variable name fixes the problem, though:

    //with a capital 'P'
    function Project(name){
        this.name = name;
    }
    
    //elsewhere...
    
    //works! class name/case is dissimilar to variable name
    let project = new Project('My Project');
    
    0 讨论(0)
  • 2020-11-27 19:00

    I've googled around also and found this solution:

    You have a variable Project somewhere that is not a function. Then the new operator will complain about it. Try console.log(Project) at the place where you would have used it as a construcotr, and you will find it.

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