我是 OOP 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);
不需要进一步的实现代码。
问题:如何在and方法中访问JS 类实例而不是window 元素。init
scroll
我知道,它不必通过this
关键字,但我仍然没有想出任何东西。
附言
addEvent
是一个非常基本的附加事件的功能,它只是对 IE/Fx 友好,没有其他功能。- 我正在编写的代码已经是功能性的,但是在程序形式上,我只是想对它进行 OOP。
- 作为一个小问题,我以某种方式得到了这样的印象,即在 javascript 中不鼓励 getter/setter 方法,如果我使用它们可以吗?