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