views:

69

answers:

2

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.

A: 

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

SHiNKiROU
so when x() is called, (which is just k masquerading as x), n is still in scope. Is that the point?
jason
@John yeah, just ran that, n is not defined
jason
and the this keyword is the window object in both functions, even inside x()
jason
I guess that site was wrong."JavaScript Scope : "Optimise" JavaScript code taking advantage of the fact a function can access all local variables in the scope of the caller." http://mindprod.com/jgloss/unmaintricks.html
SHiNKiROU
A: 

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)

indieinvader