【发布时间】:2016-10-13 05:48:28
【问题描述】:
来自 C++ 背景,尝试使用没有显式类型的 OO 语言不仅仅是头疼。
所以我有一个网页的动态元素,这些元素是由对象“控制”的,因为我需要管理大量的东西才能让它工作。元素只是对象本身内部数据的视觉输出,这就是我真正需要的。
除了我需要对象在单击时执行内部功能。到目前为止,这似乎是我头痛的最大原因。
Javascript:
function onClick(file) //The external onClick function I use to try to get it to call from.
{
file.state = INUSE;
file.checkState();
}
function fileObject () { //The file object itself
this.element;
this.newElement();
//initialize stuff for the object
}
fileObject.prototype.newElement = function() { //creates a new element and sets its event listener
this.element.click(function() {onClick(this)});
}
fileObject.prototype.checkState = function() {/*does stuff*/} //apparently this is "not a function"
我得到的错误是 Firefox 控制台面板中的“file.checkState is not a function”。
我还是 javascript 的新手,但是在进行了一些调试之后,我发现它明确地是 onClick(this) 函数导致了所有错误。当与其他东西一起使用时,onClick 函数可以完美运行,但由于某种原因,this 关键字似乎实际上并未发送对 fileObject 的引用,因为所有检查都显示file 在内部时为undefined onClick 范围的。
我尝试执行此操作的方式是否存在根本性错误,或者我只是错过了有助于使该 sn-p 工作的步骤(或添加一些我不需要的东西)。
【问题讨论】:
-
类似:
this何时变为undefined? -
好的,那我只是使用
this错误,但这仍然不能解决我的问题。我只需要一个干净的方法来传递对将在当前范围内持续存在的函数的引用。我该怎么做? -
this.element.click不是设置事件监听器的方法。 -
@torazaburo 我不确定你的意思是什么,因为它完全符合我的预期:单击元素时运行一个函数。
标签: javascript function object prototype undefined