June 29, 2012

Confuse about javascript callback function

Question by hh54188

I write two function, which callback will be invoke by the fn:

var callback = function (num) {
        return num + 1;    
}
var fn = function (callback) {
    callback();
}

fn(callback(5));

the firebug tell me: number is not a function ,I know the callback is execute immediately, how can I let it execute in the fn return the num in the fn function, the fn function is only allow the callback parameter

Answer by Elias Van Ootegem

Your example is a not great, seeing as there is no actual need for a second function. But this is what I’d do all the same:

function makeCallback(num)
{
    return function()
    {
        return num+1;
    }
}

fn = function (callback)
{
    callback.apply(this);
}

Seeing that a callback is generally called in an object context (DOM elements, when an event is handled etc) You might want to call the callback function, you passed as an argument to be called in the objects’ context.

Closures are a bit daunting and hard to fathom at first, but there are some great videos with Douglas Crockford on youtube on the matter, that really explain their workings well

Answer by Starx

It is happening due the parameter naming. The way you are using the parameters, makes a call to function called 6() which ends up being incorrect.

So, Use the following (IMO, this is what you are attempting)

var callback = function (num) {
        return num + 1;    
}
var fn = function (num) {
    callback(num);
}

fn(callback(5));

Demo

And so far for the attempt of your to create a callback function. You are only missing a return statement in the function see the result.

var callback = function (num) {
        return function(){
                return num + 1;
        };    
}
var fn = function (callback) {
    return callback();
}

console.log(fn(callback(5)));

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!