17

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?

1 Answer 1

42

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.