이 조금 추상적 일 수 있지만 나는 다음과 같은 코드를 가지고 등 자바 스크립트 폐쇄의 둘레에 내 머리를 얻으려고 :이 자바 스크립트 클로저 생성을 피하는 것이 좋습니까?
이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);
});
});
그걸로 뭘 얻으려고합니까? – Philipp
@Philipp, 나는 JavaScript closure를 만드는 것이 비쌀 수 있다는 인상하에있다. 추가 데이터가 범위 등을 추적하는 데 필요하기 때문이다.이 예에서 저축은 최소한 일지 모른다는 것을 인정하지만, 방법은 원칙적으로 * 더 좋습니다. – FixMaker