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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15008793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:08:39  来源:igfitidea点击:

Javascript: TypeError: ... is not a constructor

javascriptobjectconstructortypeerror

提问by user2089120

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

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?

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

回答by Denys Séguret

This line

这条线

var album = new album(albumName);

shadows the external albumfunction. So yes, albumisn't a constructor inside the function. To be more precise it's undefinedat this point.

遮蔽外部album功能。所以是的,album不是函数内部的构造函数。更准确地说,是undefined在这一点上。

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 guidewhen in doubt.

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