使用应用或调用作为事件处理程序的成员函数

时间:2012-04-28 05:24:45

标签: javascript node.js

对于具有this的对象成员的事件处理程序来说,更好的做法是引用调用事件处理程序的对象,还是引用事件处理程序所属的对象?

对于第一种情况,这将是一个示例:

var objects = [
    /* ... */
    {
        a: 5,
        b: 8,
        /* other member variables */
        onSomeEvent: function(data) {
            /* Do stuff with data and this.
               The a and b member variables are referenced with this.effect with the library accessed through this */
        }
    },
    /* ... */
];
function someLibrary() {
    this.doSomeEvent = function(handler, data) {
        this.effect = handler;
        handler.onSomeEvent.call(this, data);
    }
}
var someLibraryInstance = new someLibrary();
someLibraryInstance.doSomeEvent(objects[1], {c:83,d:123});

对于第二种情况,objects[1].onSomeEvent看起来像这样:

onSomeEvent: function(library, data) {
    /* Do stuff with library, data and this.
       The a and b member variables are accessed with this.a and this.b. The library is accessed through library */
}

someLibrary.doSomeEvent看起来像这样:

this.doSomeEvent = function(handler, data) {
    handler.onSomeEvent(this, data);
}

0 个答案:

没有答案