Callback functions

Man trying to understand callback functions. I have been to many articles and posts here on SO. The explanations seem circular, and I think Im really getting from understanding LOL. Ive used them, apparently, in javascript events, but more "remembers these lines" than "this is what happens and why" is understood.

So, I understand my understanding.

Say you have 2 objects, a function p () and a function k (). You pass the function k to p (). p () can then access k internal variables.

function p(x){ alert(xn);//5 } function k(){ this.n = 5; } p(k); 

Confused how long he made me get exactly that.

+4
source share
2 answers

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, the callback argument calledFunction() has the value callbackFunction , but if you notice, we are not calling the function yet, we pass a variable containing this function, and its arg function is just something before alert() . When calledFunction() is calledFunction() , it takes everything that was passed as the callback argument, and calls it with arg as its first and only argument.

Helped?

Edit: This works if you use function foo() {} -style declarations. (just in case, I don’t know how well you know JavaScript)

+4
source

You are doing it wrong. this.n = 5; in k() does not set its "internal variable" and xn accesses the property of the object x instead of the internal variable. Try the following:

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

-1
source

All Articles