I am beginner in javascript and I can't understand the powerful concept of callbacks.
I understand that as you can pass a variable as an argument to a function you can pass a function too.
Likewise I know that it is often used in asynchronous programming, but:
when I have to do that ?
what problem does this solve ?
which cases while I code should I think to pass a function as parameter to another one instead of work normally ?
Related
MY ISSUE
I've been learning the basics of AJAX from two different internet sources. In the multi-step process of sending an async HTTP request, there's one small inconsistency in how the .onload property is called on the XHR request object and then set to 1) an anonymous function or 2) a callback (??? that's what I think MDN says).
1ST APPROACH
the .onload property is called on the ourRequest object and this is set to an anonymous function:
ourRequest.onload = function() {
// the code goes here
}
2ND APPROACH
the .onload property is called on the asyncRequestObject object and this is set to the name of the function (a callback??):
function handleSuccess () {
// the code goes here
}
asyncRequestObject.onload = handleSuccess;
MY QUESTION(S)
What's the difference between how the 1st and the 2nd approach work?
And then, is there any reason to use the 1st approach over the 2nd approach?
A function declaration creates a (hoisted) variable in the current scope, that has the same name as the function, and whose value is a reference to that function.
A function expression simply evaluates as a reference to that function.
So the primary difference is that where you use handleSuccess, you can continue to reference the function for other purposes elsewhere.
What's the difference between how the 1st and the 2nd approach work?
The difference is that the first function is an anonymous function expression while the second is a function with a name. Both are event handlers for the "load" event of the XMLHttpRequest .
And then, is there any reason to use the 1st approach over the 2nd approach?
If you don't plan to reuse your handler somewhere else then you don't need to declare your function with a name.
It is no different than any other programming practice. Use a variable/constant when a value is called multiple times, otherwise use a literal.
This SO answer elegantly explains how a "function with multiple parentheses" like the one below works:
myFunction(3)(4)
But I'd like to google it and read more about it. Does this way of constructing a function have a name?
There is no such thing as a "function with multiple parentheses".
However, you can write a function that returns a function. So you pass arguments to your function with 1st parentheses, get a function in return, and pass arguments to the returned function with 2nd parentheses.
This is mainly used for IIFE when combined with closure. This technic is also called currying, as suggested by #CRice.
I've been a Javascript tinkerer for quite some time and recently I have been trying to have a real good understanding of the code I write. I want to get really good at writing Javascript. One of the things that's confused me a little bit was the usage of callback functions. I've just avoided using callbacks up until now. Right now, I'd like to know if my understanding of how a basic callback works is accurate and also if my understanding of parameters and arguments is accurate and finally, what the purpose is of using the callback in this scenario. Is there a benefit to using the callback function I've created below? If not, when are callback functions most beneficial? I realize what I've written below is quite lengthy so for the TLDR people: Am I right in thinking It's as if I created the function "theCallback" within "myFunction"? If so, what is the benefit in the scenario below? Why not just call a function? why must the function being called be an argument in the "myFunction" function?
If the scenario below doesn't make it necessary for using a callback, when is it necessary and what are the benefits? Thanks.
Here's how I see the code below: I've created a factory function "myFunction" with two parameters "x" and "callback" and parameters are pretty much variables that will be stored with arguments when the function is called. I also created another factory function "theCallback" with two parameters "x" and "theValue". Now since these are factory functions, regardless of them being underneath a function call to "myFunction", they will be hoisted above the function call so there are no problems. Had I created a function expression with a variable, they would not be hoisted. So now my call to "myFunction" has two arguments that the parameters in it will be defined as, "3" and "theCallback". The "theCallback" argument is a function. This function has the two parameters "x" and "theValue". When "myFunction" is called, "x" is stored with the argument "3" and "callback" is stored with the function "theCallback" and then the code within "myFunction" is executed which is simply a variable declared and assigned a value of a string that contains the text "for the callback" and the callback variable (I'm viewing as a variable), which was a parameter that is now an argument which is "theCallback" function I created which also contains parameters itself, is called, and given arguments for it's code to execute. In this case, the code it will execute calls the built in alert function (or method of the window object?) and gives the alert function a string argument, followed by the
alert function called again with the argument of "x" which is stored with "3" and then again alert is called and given the argument of "theValue" which contains the string "for the callback". Now when "theCallback" function is passed as a second argument to "myFunction" and it's stored in "callback", It's as if I created the function "theCallback" within "myFunction" right? If so, what is the benefit in the scenario below? Why not just call a function, why must the function being called be an argument in the "myFunction" function?
If the scenario below doesn't make it necessary for using a callback, when is it necessary and what are the benefits?
myFunction(3, theCallback);
function myFunction(x, callback){
var value = 'for the callback';
callback(x, value);
}
function theCallback(x, theValue){
alert('this is the callback function');
alert(x);
alert(theValue);
}
Is there a benefit to using the callback function I've created below?
That's a little subjective. Using a callback is unnecessary there. Normally you would return data from one function and pass it to the other.
when are callback functions most beneficial?
When you need to deal with the data after an event has fired, instead of immediately. e.g. when a button is clicked or an HTTP response has fired.
myButton.addEventListener("click", myCallbackFunction);
I've created a factory function "myFunction"
No. That is just a function. Factory functions create class objects.
they will be hoisted
Function declarations (as opposed to function expressions) are hoisted. This isn't relevant to callbacks though. A callback is basically a function passed as an argument, it doesn't matter how it was created.
what are the benefits
The benefits are that you can have different things happen when the event fires depending on the circumstance.
Take the click event example above. Often you'll want clicking on different things to have different effects, not the one thing that addEventListener was hardcoded to make happen by the browser vendor.
Following this melonJS tutorial, I'm stumped by a couple ways this callback is used (Scroll down to Part 2: Loading our level, you will see complete code)
// Set a callback to run when loading is complete.
me.loader.onload = this.loaded.bind(this);
I read this tutorial on callbacks, so I understand what they're used for... But I don't understand. It says this.loaded.bind(this)
1) What is the difference between this first and second this statements
2) what does doing bind and passing in (this) do?
Thank you
.bind(this) sets the context of the function
If you only set it to this.loaded, the context is not preserved
This might make a little more sense
var cntx = this;
me.loader.onload = function() {
cntx.loaded();
}
However, in this example, no arguments are passed to the loaded function. By using the bind one-liner, you preserve context, and you don't have to worry about any arguments being dropped along the way.
Read about Function.prototype.bind here
This is more of a general question. I have seen some answers related to it before but none gave me a clear answer.
I want to achieve an auto binding function.
example:
var someObject;
var handle = function(arg1, callback){
someObject(arg1, callback.bind(???owner of callback???))
}
var handler = new Handler();
//Calling it
handle("my arg", handler.handlerFunction);
I'm not able to control the someObject way of calling the callback as it is a third party library and it is calling my callback with a reference to itself, so I can't use this inside my prototype definitions.
I can easily achieve this by using an extra argument to the handle function sending in handler and binding to it.
Or wrapping the handler.handleFunction into an apply block, but I think it would look much better if I could just call it the way I referred to to in the codeblock.
Is it possible to find the reference to the object owning handlerFunction?
I'm using Nodejs, if that has any relevance.
Unfortunately the way you want to call it doesn't work. Here is why:
When you call handle(handler.handlerFunction) the argument you pass is a reference to a function. Any information about handler is lost there. You could do this instead:
handle("my arg", handlerFunction.bind(handler));
Or this:
handler.handlerFunction = handler.handlerFunction.bind(handler);
handle("my arg", handler.handlerFunction);
There is simply nothing like that in JavaScript for some good reason.
Instead, as you already mentioned, pass in a context variable and apply your callback to it so that it runs in the owners context. This is commonly used in many frameworks etc...