2010-11-25 103 views
0

我試圖調用類函數:的Javascript調用類函數

// Gantt chart object 
function ganttChart(gContainerID) { 

    this.isDebugMode = true;         // Is this chart in debug mode 
    this.gContainer = document.getElementById(gContainerID); // The container the chart is built inside 
    this.gDebugPannel;           // Debug pannel 

    // Create debug pannel 
    if (this.isDebugMode) { 
     this.gContainer.innerHTML += "<div id=\"gDebug" + gContainerID + "\" class=\"gDebug\">cometishian</div>"; 
     this.gDebugPannel = document.getElementById("gDebug" + gContainerID); 
    } 

    gDebug("lmfao!"); 

// Updates debug information 
function gDebug(debugMessage) { 
    alert(this.gDebugPannel.innerHTML); 
    if (this.isDebugMode) { this.gDebugPannel.innerHTML = debugMessage; } 
} 
} 

我希望它提醒「cometishian」但this.gDebugPannel.innerHTML爲空,任何想法?

經過進一步調查,this.gDebugPannel未定義。

更新:

// Gantt chart object 
function ganttChart(gContainerID) { 

    this.isDebugMode = true;         // Is this chart in debug mode 
    this.gContainer = document.getElementById(gContainerID); // The container the chart is built inside 
    this.gDebugPannel;           // Debug pannel 
    this.gPosX; 
    this.gPosY; 

    // Create debug pannel 
    if (this.isDebugMode) { 
     this.gContainer.innerHTML += "<div id=\"gDebug" + gContainerID + "\" class=\"gDebug\">5,5 | 5.1</div>"; 
     this.gDebugPannel = document.getElementById("gDebug" + gContainerID); 
    } 

    // Updates debug information 
    ganttChart.gDebug = function(debugMessage) { 
     if (this.isDebugMode) { this.gDebugPannel.innerHTML = debugMessage; } 
    } 

    this.gDebug("wo"); 

} 

行this.gDebug(在 「wo」)拋出:

網頁錯誤的詳細信息

用戶代理:Mozilla的/ 4.0(兼容; MSIE 8.0; Windows NT的5.1; Trident/4.0; InfoPath.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 1.1.4322; .NET CLR 3.0.4506.2152; .NET CLR 3.5。 30729; OfficeLiveConnector.1.4; OfficeLivePatch.1.3) 時間戳:Thu,25 Nov 2010 12:57:51 UTC

Message: Object doesn't support this property or method 
Line: 21 
Char: 5 
Code: 0 
URI: http://server1/bb/ganttnew/gMain.js 
+0

聲明`this.gDebugPannel;`什麼都不做。 – SLaks 2010-11-25 12:51:11

+0

panel has 1`n` btw ... – brad 2010-11-25 13:03:08

回答

1

你需要呼籲this實例的功能,如:

gDebug.call(this, "Hi!"); 

做到這一點,正確的做法是把功能的類原型:(這應該是後進行聲明構造函數)

ganttChart.prototype.gDebug = function(debugMessage) { 
    alert(this.gDebugPannel.innerHTML); 
    if (this.isDebugMode) { this.gDebugPannel.innerHTML = debugMessage; } 
} 

this.gDebug("Hi!"); 
1

你也可以做到這一點作爲

this.gDebug= function(debugMessage) { 
    alert(this.gDebugPannel.innerHTML); 
    if (this.isDebugMode) { this.gDebugPannel.innerHTML = debugMessage; } 
}