2010-11-10 65 views
1

試圖讓我的頭繞着Javascript發生了一件非常奇怪的事情。即使我沒有明確地調用它,方法getChapters()也會觸發...任何想法? (我得到了獲取章節的警告框)。即使我沒有調用它,爲什麼這個javascript方法會觸發?

videoChapters = function() { 
}; 

videoChapters.prototype.config = { 
    jsonProvider : '_Chapters.aspx' 
}; 

videoChapters.prototype.init = function() { 
    //get chapters 
}; 

videoChapters.prototype.getChapters = new function() { 
    alert('getting chapters'); 
} 

jQuery(document).ready(function() { 
    videoChapters = new videoChapters(); 
    videoChapters.init(); 
}); 

回答

3

這條線:

videoChapters.prototype.getChapters = new function() { 

...可能不應該包含單詞 '新'。當Javascript嘗試評估表達式時,它會將函數的結果傳遞給「新」運算符。

2

刪除new關鍵字:

videoChapters.prototype.getChapters = function() { 
    alert('getting chapters'); 
} 
1
....prototype.getChapters = new function() { 
          ^-------- See the new keyword here? 

取出new關鍵字,一切都將如預期,用new將調用函數作爲構造函數,返回它的一個新的實例,在這種情況下,匿名函數的新實例。

相關問題