Javascript: TypeError: ... is not a constructor

user2089120 picture user2089120 · Feb 21, 2013 · Viewed 81.7k times · Source

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?

Answer

Denys S&#233;guret picture Denys Séguret · Feb 21, 2013

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.