【发布时间】:2010-12-03 17:10:26
【问题描述】:
给定:
myChart = new ganttChart("chart1");
function ganttChart(gContainerID) {
this.variable1 = "lol";
this.variable2 = "hai dere";
this.variable3 = "cometishian";
....
this.gContainer = document.getElementById(gContainerID);
this.gContainer.innerHTML += "<div id=\"gBar" + i +
"\" class=\"gBar\" onmousedown=\"gInitBarDrag(this)\">Hello</div>";
....
}
如何在 ganttChart 类中定义函数 gInitBarDrag()?我不想要一个外部独立函数,因为它需要引用对象内部的东西。
因此,例如,该函数将能够引用在 ganttChart 对象的特定实例中定义的变量 1/2/3(您可以有多个图表对象)。
希望这是有道理的!例如:
function ganttChart(gContainerID) {
this.variable1 = "lol";
this.variable2 = "hai dere";
this.variable3 = "cometishian";
....
this.gContainer.innerHTML += "<div id=\"gBar" + i +
"\" class=\"gBar\" onmousedown=\"gInitBarDrag(this)\">Hello</div>";
....
gInitBarDrag = function(thisGanttObject)
{
alert(thisGanttObject.variable2);
// This line wont work because it doesn't know what ganttChart to reference!
}
}
【问题讨论】:
-
@Tom
this值指向什么? -
@Tom 你所说的“granttChart 类”是什么意思? granttChart 是一个函数,反正 JavaScript 中没有类。
-
我认为您可以尝试附加一个事件而不是在标记中声明它,并在 ganttChart 中引用该函数。现在的大多数 JS 框架都应该有一个 API 来将事件附加到 DOM 对象。我没有发布答案,因为我现在无法尝试编写代码。如果我回到家时还没有回答,我会尝试为您获取一些工作代码。
-
@Tom Aha,那么它是一个构造函数吗?
-
我已经改写了,是的,innerHTML 部分是对象构造函数的一部分
标签: javascript function object