これは少し抽象的なかもしれませんが、JavaScriptクロージャなどに頭を悩ませようとしています。次のコードを使用してください。
function MyObj() {
var me = this;
this.foo = function(bar) {
// Do something with 'bar'
}
// Set up lots of local variables etc.
// ....
$(window).load(function() {
// Add a delegated click handler to specific <input> elements
$(document).on('click.myobj', 'input.special', function() {
// Do something with the <input> that triggered the click event
me.foo(this);
});
});
}
var myObj = new MyObj();
クリックイベントにバインドされて渡された無名関数は、を参照するクロージャを作成しますme
。私が知りたいのは、代わりにこのようなことをする方が良いかどうかです(閉鎖を避けるため):
$(window).load(function() {
// Add a delegated click handler to specific <input> elements
(function(localMe) {
$(document).on('click.myobj', 'input.special', function() {
// Do something with the <input> that triggered the click event
localMe.foo(this);
});
})(me);
});
これはより良いアプローチですか、それとも私はクロージャーを作成することについて過度に妄想していますか?あるいは、「第三の道」はありますか?
編集
さらに、次のようなことを行う方がよいでしょうか。
$(window).load(function() {
// Add a delegated click handler to specific <input> elements
$(document).on('click.myobj', 'input.special', {localMe : me}, function(event) {
// Do something with the <input> that triggered the click event
event.data.localMe.foo(this);
});
});