Javascript: TypeError: ... 不是构造函数 [英] 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;
}
}
给出以下错误:
TypeError:专辑不是构造函数
我找不到问题.我阅读了很多其他帖子,但找不到类似的问题.难道是不允许在另一个对象中创建一个对象?我该如何解决这个问题?
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?
推荐答案
此行
var album = new album(albumName);
隐藏外部album
功能.所以是的,album
不是函数内部的构造函数.更准确地说,此时它是 undefined
.
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) {
更一般地说,我建议在使用时遵循 Google 风格指南怀疑.
More generally I'd suggest to follow the Google style guide when in doubt.
这篇关于Javascript: TypeError: ... 不是构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!