开发者

callback functions

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.


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)


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜