Javascript: TypeError: ... is not a constructor

86,621

This line

var album = new album(albumName);

shadows the external album function. So yes, album isn't a constructor inside the function. To be more precise it's undefined at this point.

To avoid this kind of problem, I'd suggest naming your "classes" starting with an uppercase :

function Album(name) {

More generally I'd suggest to follow the Google style guide when in doubt.

Share:
86,621
user2089120
Author by

user2089120

Updated on June 11, 2020

Comments

  • user2089120
    user2089120 about 4 years

    I have a TypeError problem:

    function artist(name) {
        this.name = name;
        this.albums = new Array();
    
        this.addAlbum = function(albumName) {
            for (var i = 0; i < this.albums.length; i++) {
                if (this.albums[i].name == albumName) {
                    return this.albums[i];
                }
            }
    
            var album = new album(albumName);
            this.albums.push(album);
    
            return album;
        }
    }
    
    function album(name) {
        this.name = name;
        this.songs = new Array();
        this.picture = null;
    
        this.addSong = function(songName, track) {
            var newSong = new songName(songName, track);
            this.songs.push(newSong);
    
            return newSong;
        }
    }
    

    gives the following error:

    TypeError: album is not a constructor

    I can't find the problem. I read a lot of other posts, but I could not find a similar problem. Could it be that it's not allowed to create an object in another object? How I can solve this problem?

  • Felix Kling
    Felix Kling over 11 years
    It's equivalent to var album; album = new album(albumName);. That should make it more obvious.
  • user2089120
    user2089120 over 11 years
    @Felix Kling: Thanks also for your help! I wrote "var album; album = new Album(albumName);" => but without success
  • iiminov
    iiminov over 9 years
    Thanks that helped me out of bind. Nice explanation @dystroy.