1

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);
}
4

0 回答 0