Man Im trying to understand callback functions. Ive been over many articles and posts here on SO. The explanations seem circular and I think Im actually getting farther from understanding lol. Ive used them apparently in javascript events, but its more a 'memorize these lines' than 'this is whats going on and why' sort of understanding.
So heres my understanding.
Say you have 2 objects, function p() and function k(). You pass function k to p(). p() can then access k's inner variables.
function p(x){
alert(x.n);//5
}
function k(){
this.n = 5;
}
p(k);
Embarrassing how long its taken me to get just this.
-
1I think you might be confusing callbacks with closuresAlex Mcp– Alex Mcp2010年09月04日 05:55:25 +00:00Commented Sep 4, 2010 at 5:55
-
1great... wtf is a closure... fml lol, srsly need to go to bed nowjason– jason2010年09月04日 06:02:30 +00:00Commented Sep 4, 2010 at 6:02
-
3don't apologize, i have an IQ of 140, an expensive education, and have spent probably 60% of my waking hours on a computer, and I still don't comprehend them. they seem.. so convoluted... why muck-up the process with what boils down to a wildly unpredictable error routine? separate that shit. i hate them.Alex Gray– Alex Gray2011年09月12日 02:43:48 +00:00Commented Sep 12, 2011 at 2:43
2 Answers 2
Maybe an example will help?
// First, lets declare the function we're going to call
calledFunction = function (callback, arg) {
callback(arg);
};
// Second, lets declare the callback function
callbackFunction = function (arg) {
alert(arg);
};
// Next, lets do a function call!
calledFunction(callbackFunction, "HAI");
So, calledFunction()'s callback argument is callbackFunction but, if you notice, we aren't calling the function yet, we're passing a variable the contains the function, and its arg function is just something to alert(). When calledFunction() is executed it takes whatever was passed as the callback argument and calls it with arg as its first, and only, argument.
Helped?
Edit: This still works if you use function foo() {}-style declarations. (just in case; I don't know how fluent you are with JavaScript)
Comments
You are doing it wrong. this.n = 5; in k() does not set its "inner variable", and x.n access the function object's x property, instead of its inner variable.
Try this:
function p(x) { alert(new x().n); }
Variable binding is an important programming concept.
I think this article helps. http://www.hunlock.com/blogs/Functional_Javascript