开发者问题收集

Javascript:类型错误:...不是构造函数

2013-02-21
91651

我遇到了 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 construction

我找不到问题所在。我读了很多其他帖子,但没有找到类似的问题。难道是不允许在另一个对象中创建对象?我该如何解决这个问题?

1个回答

此行

var album = new album(albumName);

遮蔽了外部 album 函数。所以,是的, album 不是函数内的构造函数。更准确地说,此时它是 undefined

为了避免此类问题,我建议以大写字母开头命名您的“类”:

function Album(name) {

更一般地,我建议在有疑问时遵循 Google 风格指南

Denys Séguret
2013-02-21