JavaScript 함수를 호출 할 때 "this"의 사용자 정의 값을 어떻게 설정합니까?
-
06-09-2019 - |
문제
나는 jQuery를 사용하고 있으며 이벤트 콜백 역할을하는 함수가 있으므로 그 기능에서 "이것은"이벤트를 캡처 한 객체를 나타냅니다. 그러나 다른 함수에서 기능을 명시 적으로 호출하려는 인스턴스가 있습니다.이 경우 함수 내에서 "이"가 동일한 것을 어떻게 설정합니까?
예를 들어:
function handleEvent(event) {
$(this).removeClass("sad").addClass("happy");
}
$("a.sad").click(handleEvent); // in this case, "this" is the anchor clicked
function differentEvent(event) {
$("input.sad").keydown(e) {
doSomeOtherProcessing();
handleEvent(e); // in this case, "this" will be the window object
// but I'd like to set it to be, say, the input in question
}
}
다른 팁
관심있는 기능을 매개 변수화하십시오.
function doStuff(el) {
$(el).removeClass("sad").addClass("happy");
}
function handleEvent(event) {
doStuff(this);
}
$("a.sad").click(handleEvent); // in this case, "this" is the anchor clicked
function differentEvent(event) {
$("input.sad").keydown(e) {
doSomeOtherProcessing();
doStuff(this);
}
}
사용
e.target
jQuery 플러그인으로서의 기능을 재현하는 조언을드립니다.
그러나 여기에 빠른 수정이 있습니다.
handleEvent.apply(this,e) //transfers this from one scope, to another
단순히 단일 이벤트 핸들러를 마치 정상적으로 트리거되는 것처럼 호출하려는 경우 apply
/call
잘 작동합니다. 그러나 귀하의 요구에 따라 jQuery의 제로 변호 버전을 사용하는 것이 더 강력 할 수 있습니다. 딸깍 하는 소리() 트리거되는 기능 모두 해당 요소에 대한 핸들러를 클릭하십시오.
function differentEvent(event) {
$("input.sad").keydown(e) {
doSomeOtherProcessing();
$(this).click(); // simulate a click
}
}
제휴하지 않습니다 StackOverflow