2013-02-21 24 views
15

mam problem Błąd typu:JavaScript: Błąd typu: ... nie jest konstruktorem

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

daje następujący błąd:

TypeError: album is not a constructor

nie mogę znaleźć problem. Czytałem wiele innych postów, ale nie mogłem znaleźć podobnego problemu. Czy to możliwe, że nie wolno tworzyć obiektu w innym obiekcie? Jak mogę rozwiązać ten problem?

Odpowiedz

40

Linia

var album = new album(albumName); 

cienie zewnętrzny album funkcyjnych. Więc tak, album nie jest konstruktorem wewnątrz funkcji. A dokładniej, w tym miejscu jest undefined.

Aby uniknąć tego rodzaju problemu, polecam nazywania „klas” zaczynające się wielką literą:

function Album(name) { 

Bardziej ogólnie sugeruję pójść the Google style guide w razie wątpliwości.

+10

Jest to odpowiednik 'var album; album = nowy album (nazwa albumu); '. To powinno uczynić to bardziej oczywistym. –

+0

@Felix Kling: Dziękuję również za pomoc! Napisałem "var album; album = new Album (nazwa albumu);" => ale bez powodzenia – user2089120

+1

@ user2089120 Zobacz http://jsbin.com/uhapel/1/edit (otwórz konsolę) –

Powiązane problemy