gpt4 book ai didi

Javascript 调用类函数

转载 作者:行者123 更新时间:2023-12-02 20:30:21 26 4
gpt4 key购买 nike

我正在尝试调用类函数:

// 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)时间戳:2010 年 11 月 25 日星期四 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

最佳答案

您需要在 this 实例上调用该函数,如下所示:

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

正确的做法是将函数放在类原型(prototype)中:(这应该在声明构造函数之后完成)

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

this.gDebug("Hi!");

关于Javascript 调用类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4277205/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com