2016-04-20 23 views
-1

大家好! 我真的需要你的幫助,因爲我無法弄清楚爲什麼它不起作用。 我寫的錯誤是:Uncaught TypeError:playlist1.toHTML不是函數

Uncaught TypeError: playlist1.toHTML is not a function

JS:

function test(){ 
    var playlist1 = new Playlist(); 
    var music1 = new Music('theurl'); 
    var music2 = new Music('anotherUrl'); 
    var container = document.getElementById('results'); 
    container.innerHTML = playlist1.toHTML(); 
} 
var id=0; 
function Music(url){ 
    this.id=id+1; 
    this.url=url; 
    this.name="unknown"; 
    this.author="unknown"; 
    this.album="unknown"; 
    this.cover="unknown"; 
} 
var nb=0; 
function Playlist(){ 
    nb=nb+1; 
    this.elements = []; 
    this.nom = 'playlist'+nb; 
} 
function toHTML(){ 
    var text=""; 
    for(var i=0; i<this.elements.length; i++){ 
     text+= "<li>\n"; 
     text+= "<div>\n"; 
     text+= "<figure class='music' track='"+this.elements[i].getUrl()+"'></figure>"; 
     text+= "<img src='"+this.elements[i].getCover()+"'>\n"; 
     text+= "</div>\n"; 
     text+= "<div>\n"; 
     text+= "<h3>"+this.elements[i].getName()+"</H3>\n"; 
     text+= "<h4>"+this.elements[i].getAuthor()+" - "+this.elements[i].getAlbum()+"</H4>\n"; 
     text+= "</div>\n"; 
     text+= "</li>\n"; 
    } 
    return text; 
} 

HTML:

<!DOCTYPE html> 
<html> 
    <head> 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> 
     <script src="arrays.js"></script> 
    </head> 
    <body> 
     <button onclick="test()">Make it</button> 
     <p id="results"></p> 
    </body> 
</html> 

我會真的請如果有人可以幫助我解決這個問題:)

+1

您的播放列表定義中的this.toHTML = toHTML'也許? – IrkenInvader

+0

你好,謝謝你試圖幫助我,但我不認爲我理解你的評論? - IrkenInvader – 0dium

+0

'function Playlist(){ nb = nb + 1; this.elements = []; this.nom ='playlist'+ nb; this.toHTML = toHTML; }' – IrkenInvader

回答

0

類方法沒有像你的那樣定義。它應該寫在新類的prototype的定義中。

var SomeObject = function(data) { 
    this.data = data; 
} 

SomeObject.prototype = { 
    Output: function(dom) { 
     dom.innerHTML += this.data + "<br/>"; 
    } 
} 

var a = new SomeObject("value"); 
a.Output(document.querySelector("#log")); 

看看如何Mozilla Developer Network teaches OO,你會在JS更好的編碼OO,也許。 =)

+0

對不起,我不習慣JavaScript。我會檢查你的鏈接,找出它是如何工作的,謝謝! – 0dium

+0

沒關係,練習變得更好! –

+0

當然,我測試了我的獲得者和問題不是來自那些 – 0dium

0

您正嘗試在播放列表中調用toHTML,但您尚未定義func播放列表對象上。

所以爲了使用container.innerHTML = playlist1.toHTML();

你需要做播放列表對象中的該功能的一部分。

function Playlist(){ 
    nb=nb+1; 
    this.elements = []; 
    this.nom = 'playlist'+nb; 
    this.toHTML = toHTML; 
} 
+0

謝謝!我會改變的! – 0dium

相關問題