Javascript:TypeError:...不是构造函数

时间:2013-02-21 17:39:12

标签: javascript object constructor typeerror

我遇到TypeError问题:

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;
    }
}

给出以下错误:

TypeError: album is not a constructor

我找不到问题。我阅读了很多其他帖子,但我找不到类似的问题。难道不允许在另一个对象中创建一个对象吗?我怎么能解决这个问题?

1 个答案:

答案 0 :(得分:40)

这一行

var album = new album(albumName);

隐藏外部album函数。所以是的,album不是函数内部的构造函数。更准确地说,此时undefined。{/ p>

为了避免这种问题,我建议以大写字母命名你的“类”:

function Album(name) {

更常见的是,我建议在有疑问时关注the Google style guide