Javascript “Not a Constructor” Exception while creating objects

后端 未结 14 1192
[愿得一人]
[愿得一人] 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');
    

提交回复
热议问题