Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: TypeError: ... is not a constructor

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?

like image 982
user2089120 Avatar asked Feb 21 '13 17:02

user2089120


1 Answers

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.

like image 151
Denys Séguret Avatar answered Oct 01 '22 00:10

Denys Séguret