You have to define functions (i.e. the callbacks) within functions.
1 function function1(){
2 function2(function(obj) {
3 console.log(obj); //logs obj.
});
}
4 function function2(callbackFn){
//do stuff with DB and get obj
console.log(obj); //logs obj.
5 callbackFn(obj);
}
function2
can be called from many places at once, not just function1
.
If you can be more specific about what you don't understand, then you might get a better answer.
Functions are values, just like numbers, strings and objects.
This is the core fundamental of functional programming, and probably the thing you haven't grasped. In JavaScript, as in a number of languages, functions are not special*. This is different to languages like C or Java, where functions/methods are different to the usual values you deal with in your code.
2; // Here is a number
var a = 2; // I can assign it to a variable
console.log(2); // I can pass it as a function argument
function() {} // Here is a function
var a = function() {}; // I can assign it to a variable
console.log(function() {}); // I can pass it as a function argument
function jim() {} // This function's name is jim
var a = jim; // I can assign it to a variable
console.log(jim); // I can pass it as a function argument
(function() {})(); // I can call a function without giving it any names
jim(); // I can call a named function
a(); // I can call a function via a variable
jim.call(this, arg1); // Or I can get complicated
So, we can declare functions and pass them around, separately to calling them. Now, what about the code we started with.
- Declare a new function called
function1
that takes no arguments - When
function1
is called, callfunction2
with a single argument, a new nameless function that takes anobj
argument - When the anonymous function is called, call
console.log
with the value passed forobj
- Declare a new function called
function2
that takes a single argumentcallbackFn
- Call the value passed for
callbackFn
with a single argument, theobj
we got from somewhere
So the declaration order is 1, 4, 2; and the execution order is 2, 5, 3.
*OK, they're a little special. Their definitions are hoisted, you can execute the code they represent, and their declarations create scope and closures. But those are all questions for another time.