exports.list = function(callback){
var result = model.find({}, function(err, objects){
callback(null, objects)
});
return result;
}
Q: Why is the above code a closure? Is it because the function parameter calls the function callback which is nested in it?
Q: does this cause an infinite loop, since the function is calling itself through its parameter?
Q: will the above function work if callback wasn't defined anywhere?
-
1One could argue that all JS functions are closures, as the parent scope is there automatically (with no extra work on your part) if you want variables from it. Some just don't use those variables (yet).cHao– cHao2012年11月02日 21:01:16 +00:00Commented Nov 2, 2012 at 21:01
3 Answers 3
The others have already answered most of your questions. However, from your comments I see that you may still be confused about the last question:
- Q: will the above function work if callback wasn't defined anywhere?
Answer: callback is already defined in the above code. And here's where callback is defined:
exports.list = function(callback){ // <---- the callback variable defined here
var result = model.find({}, function(err, objects){
callback(null, objects) // <-- callback is used here
});
return result;
}
Now, by the strict meaning of the word "defined", callback is defined as the parameter of eports.list(). If you pass anything other than a function (or nothing) the exports.list() callback would still technically be "defined" but its value would not be a function.
1 Comment
Q: Why is the above code a closure? Is it because the function parameter calls the function callback which is nested in it?
A: As Mike explained, once an outside var is used inside a function, you create a closure.
Q: does this cause an infinite loop
A: I assume function(err, objects) will fire only once for the model, so no it won't. You would create an infinite loop if you call callee (or self)
Q: will the above function work if callback wasn't defined anywhere?
A: you will get an error ReferenceError: callback is not defined
1 Comment
ReferenceError: callback is not defined if i call exports.list(), where callback is not defined elsewhereit is a closure because callback is captured inside the model.find() code from enclosing function scope assigned to exports.list.
5 Comments
callback being called by other functions outside the scope of listexports.list(function(arg1, objList) { console.log("stuff"); })callback right? As i dont see it being defined as a function elsewhere..callback is already defined in your code. Here: exports.list = function(callback){ // <-- callback defined here