함수에 매개 변수로 전달 된 메소드를 실행하는 방법
콜백 메서드를 매개 변수로 사용하고 완료 후 실행하는 JavaScript에서 자체 함수를 작성하고 싶습니다. 인수로 전달되는 메서드에서 메서드를 호출하는 방법을 모르겠습니다. 반사처럼.
예제 코드
function myfunction(param1, callbackfunction)
{
//do processing here
//how to invoke callbackfunction at this point?
}
//this is the function call to myfunction
myfunction("hello", function(){
//call back method implementation here
});
일반 함수로 호출 할 수 있습니다.
function myfunction(param1, callbackfunction)
{
//do processing here
callbackfunction();
}
유일한 추가 사항은 컨텍스트 를 언급하는 것입니다 . this콜백 내 에서 키워드 를 사용하려면 할당해야합니다. 이것은 종종 바람직한 행동입니다. 예를 들면 :
function myfunction(param1, callbackfunction)
{
//do processing here
callbackfunction.call(param1);
}
콜백에서, 당신은 지금에 액세스 할 수 있습니다 param1로 this. 을 참조하십시오 Function.call.
나도 다른 함수에 매개 변수로 보낸 함수를 호출해야하는 동일한 시나리오에 들어갔다.
나는 시도했다
mainfunction('callThisFunction');
첫 번째 접근
function mainFuntion(functionName)
{
functionName();
}
그러나 결국 오류가 발생합니다. 그래서 나는 시도했다
두 번째 접근
functionName.call().
여전히 사용하지 않습니다. 그래서 나는 시도했다
세 번째 접근
this[functionName]();
챔피언처럼 작동했습니다. 그래서 이것은 단지 하나의 호출 방법을 추가하는 것입니다. 내 첫 번째 및 두 번째 접근 방식에 문제가있을 수 있지만 대신 인터넷 검색을 더 많이하고 세 번째 접근 방식으로 시간을 보냈습니다.
function myfunction(param1, callbackfunction)
{
//do processing here
callbackfunction(); // or if you want scoped call, callbackfunction.call(scope)
}
object[functionName]();
object : 개체 의 이름을 나타냅니다.
functionName : 함수 를 호출하는 데 사용할 값을 가진 변수입니다.
by putting the variable used to refer to the function name inside the [] and the () outside the bracket we can dynamically call the object's function using the variable. Dot notation does not work because it thinks that 'functionName' is the actual name of the function and not the value that 'functionName' holds. This drove me crazy for a little bit, until I came across this site. I am glad stackoverflow.com exists <3
Another way is to declare your function as anonymous function and save it in a variable:
var aFunction = function () {
};
After that you can pass aFunction as argument myfunction and call it normally.
function myfunction(callbackfunction) {
callbackfunction();
}
myfunction(aFunction);
However, as other answers have pointed out, is not necessary, since you can directly use the function name. I will keep the answer as is, because of the discussion that follows in the comments.
I will do something like this
var callbackfunction = function(param1, param2){
console.log(param1 + ' ' + param2)
}
myfunction = function(_function, _params){
_function(_params['firstParam'], _params['secondParam']);
}
Into the main code block, It is possible pass parameters
myfunction(callbackfunction, {firstParam: 'hello', secondParam: 'good bye'});
All the examples here seem to show how to declare it, but not how to use it. I think that's also why @Kiran had so many issues.
The trick is to declare the function which uses a callback:
function doThisFirst(someParameter, myCallbackFunction) {
// Do stuff first
alert('Doing stuff...');
// Now call the function passed in
myCallbackFunction(someParameter);
}
The someParameter bit can be omitted if not required.
You can then use the callback as follows:
doThisFirst(1, myOtherFunction1);
doThisFirst(2, myOtherFunction2);
function myOtherFunction1(inputParam) {
alert('myOtherFunction1: ' + inputParam);
}
function myOtherFunction2(inputParam) {
alert('myOtherFunction2: ' + inputParam);
}
Note how the callback function is passed in and declared without quotes or brackets.
- If you use
doThisFirst(1, 'myOtherFunction1');it will fail. - If you use
doThisFirst(1, myOtherFunction3());(I know there's no parameter input in this case) then it will callmyOtherFunction3first so you get unintended side effects.
참고URL : https://stackoverflow.com/questions/6001149/how-to-execute-a-method-passed-as-parameter-to-function
'Program Club' 카테고리의 다른 글
| Linux 쉘 스크립트에서 정규식을 사용하여 파일을 검색하는 방법 (0) | 2020.12.08 |
|---|---|
| 누구든지 nodejs를 사용하여 git 복제 또는 인터페이스 라이브러리를 구현 했습니까? (0) | 2020.12.08 |
| 위치 : 상대로 항목 중앙 (0) | 2020.12.08 |
| setInterval CPU 집약적입니까? (0) | 2020.12.08 |
| 이 간단한 문자열이 유효한 JSON으로 간주됩니까? (0) | 2020.12.08 |