我是 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);
不需要进一步的实现代码。
问题:如何访问JS类实例 in the init
and scroll
方法和not the 窗口元素.
它不必通过this
关键字,我知道,但我仍然没有想出任何东西。
P.S.
-
addEvent
是一个非常基本的附加事件的函数,它只是 IE/Fx 友好的,不执行任何其他操作。
- 我正在编写的代码已经可以运行,但在过程形式中,我只是想对其进行 OOP。
- 作为一个小问题,我的印象是,在 JavaScript 中不鼓励使用 getter/setter 方法,如果我使用它们可以吗?
我注意到的一件事是init
nor scroll
是实例上的方法。
所以你只需要添加init
并不是this.init
到加载事件:
addEvent(window,'load',init); // No "this." needed
同样:
addEvent(window,'scroll',scroll);
如果您决定将他们转移到班级(例如this.scroll
and this.init
等),您可以保存对this
并在传递给的匿名函数中引用它addEvent
:
var self = this;
this.init = function() {
addEvent(window, 'scroll', function() {
self.scroll()
})
};
this.scroll = function() { /* ... */ };
addEvent(window,'load',function() {
self.init()
});
这被称为closure https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Working_with_Closures.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)