对于具有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);
}