我刚接触面向对象的JavaScript,对于“this”关键字和事件处理有些困惑。
我的目标是:我有多个DOM对象,不仅要将一个公共事件绑定到它们上面,还要在全局容器中保存这些对象的一些数据(以提高运行时性能)。
所以,我基本上是这样做的:
function ClassThatDoesSomething() {
/* keeps node ids for processing in this.init */
this.nodes = new Array();
/* keeps processed node data for fast access */
this.nodeData = new Array();
this.sthAddNodes = function(/* ids */) {
/* appends node ids to local variable (this.nodeData) */
}
function init() {
/* gathers data from all nodes that were
added before and stores it in this.nodeData */
/* here, unsurprisingly, 'this' references the window element*/
addEvent(window,'scroll',this.scroll);
}
function scroll() {
/* do stuff when user scrolls the page */
/* 'this' references the window element here too */
}
addEvent(window,'load',this.init);
}
稍后,在文档正文中,我可以添加以下内容:
var Ctds = new ClassThatDoesSomething();
接着,通过以下方法添加DOM元素:
Ctds.addNodes(ids);
不需要进一步的实现代码。
问题:如何在init
和scroll
方法中访问JS类实例,而不是window元素。
它不必通过this
关键字,我知道,但我仍然想不出什么。
P.S.
addEvent
是一个极为基本的函数,用于附加事件,它只是IE/Fx友好,并且不执行其他操作。- 我正在编写的代码已经具有功能性,但以过程化形式,我只是想将其转换为面向对象。
- 作为一个次要的子问题,我得到了这样的印象,即getter/setter方法在javascript中被不鼓励使用,如果我使用它们可以吗?