Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to write my own function in JavaScript which takes a callback method as a parameter and executes it after the completion, I don't know how to invoke a method in my method which is passed as an argument. Like Reflection.

example code

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
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
179 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can just call it as a normal function:

function myfunction(param1, callbackfunction)
{
    //do processing here
    callbackfunction();
}

The only extra thing is to mention context. If you want to be able to use the this keyword within your callback, you'll have to assign it. This is frequently desirable behaviour. For instance:

function myfunction(param1, callbackfunction)
{
    //do processing here
    callbackfunction.call(param1);
}

In the callback, you can now access param1 as this. See Function.call.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...