Javascript:将OOP方法附加到事件和'this'关键字

rav*_*ren 4 javascript oop this event-handling

我是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);
}
Run Code Online (Sandbox Code Playgroud)

稍后,在文档正文中,我可以添加:

var Ctds = new ClassThatDoesSomething();
Run Code Online (Sandbox Code Playgroud)

接下来,通过以下方式添加DOM元素:

Ctds.addNodes(ids);
Run Code Online (Sandbox Code Playgroud)

不需要进一步的实施代码.

问:如何访问 JS类的实例initscroll方法,并没有窗口元素.

this我知道,它不一定要通过关键字,但我仍然没有想出任何东西.

PS

  • addEvent 是一个非常基本的功能来附加事件,它只是IE/Fx友好,没有别的.
  • 我正在编写的代码已经可以使用了,但是在程序形式上,我只是想对它进行OOP.
  • 作为一个次要的子问题,我得到了一些印象,在javascript中不鼓励使用getter/setter方法,如果我使用它们可以吗?

Roa*_*rth 10

我注意到的一件事是,实例上既不是init也不scroll是方法.

所以你只需要添加init而不是this.init加载事件:

addEvent(window,'load',init); // No "this." needed
Run Code Online (Sandbox Code Playgroud)

同样地:

addEvent(window,'scroll',scroll);
Run Code Online (Sandbox Code Playgroud)

如果你决定将它们移到类(如this.scrollthis.init等),你可以保存到一个参考this和引用它传递给一个匿名函数addEvent:

var self = this;

this.init = function() {
    addEvent(window, 'scroll', function() {
        self.scroll()
    })
};

this.scroll = function() { /* ... */ };

addEvent(window,'load',function() {
    self.init()
});
Run Code Online (Sandbox Code Playgroud)

这称为闭包.