2016-05-09 57 views
3

我正在嘗試將示例代碼與另一個站點的示例代碼一起使用。JavaScript原型示例

我簡化了代碼並將其列在下面。當我使用它時,我得到以下錯誤:TypeError:this.createChart不是一個函數。我沒有在jsfiddle上得到這個錯誤,只是當我試圖實現代碼我的網站。

我工作的jsfiddle是在這裏:http://jsfiddle.net/56vjtv3d/76

有什麼建議?謝謝!

function Meteogram(A,B) { 
     this.A = A; 
     this.B = B; 
     this.createChart(); 
    } 

    Meteogram.prototype.createChart = function() { 
     alert('test'); 
     //Will do other stuff here 
    }; 
+1

此代碼(加上'新的天氣圖表()',當然)正在爲我工​​作,而且我在JSFiddle中看不到任何錯誤。 –

+0

我粘貼在控制檯..它的工作原理。 – animaacija

+1

你必須向我們展示不起作用的代碼。 – Bergi

回答

2

此代碼工作正常,你可能不進行初始化你的對象/ s的正確

您的天氣圖表功能被稱爲「對象的構造函數」,其有用創建幾個類似的對象,並創建新對象從這個構造函數,你需要使用關鍵字

我們已經有這樣:

function Meteogram(A,B) { 
    this.A = A; 
    this.B = B; 
    this.createChart(); 
} 

Meteogram.prototype.createChart = function() { 
    alert('test'); 
    //Will do other stuff here 
} 

現在..

這將工作

var m = new Meteogram('a', 'b'); 
// Now m is an instance of Meteogram !! 

這不會

var m = Meteogram('a', 'b'); 
// Uncaught TypeError: this.createChart is not a function(…) 
+1

我能夠得到它的工作。我在代碼中沒有正確初始化。感謝您的幫助! – Aquabug222