Alexander Mills
Alexander Mills

Reputation: 100000

Anonymous functions - my perennial undertaker

I have used anonymous functions with Java and now with JavaScript, and I still don't understand one thing.

With JavaScript, we might have the following code:

doSomething('omg',function(mark){
    console.log(mark);
});

function doSomething(printthis,callback){
    console.log(printthis);
    callback();
}

so we pass 'omg' and an anonymous function to the doSomething function.

However, where does the parameter/argument 'mark' come from? How do we pass this anonymous function the mark parameter? I swear I have seen this done time and time again, but I don't know where the mark parameter comes from.

Where?

Upvotes: 0

Views: 36

Answers (3)

StackSlave
StackSlave

Reputation: 10627

You are missing how passing an argument to a user defined function works:

function doSomething(printThis, callback, context){
  var c = context || this; // if you need to bind the context of callback
  callback.call(c, printThis); // your callback is passed printThis
}
doSomething('omg', function(mark){
  console.log(mark);
});

You actually define the argument which you pass to your user defined function in your function which executes the callback.

Upvotes: 0

EvilZebra
EvilZebra

Reputation: 1072

The best method would be to use bind, but keep in mind that this will need to be set, or null.

doSomething('omg',function(mark){
    console.log(mark);
}.bind(null, 'test'));

function doSomething(printthis,callback){
    console.log(printthis);
    callback();
}

jsfiddle

This can also be achieved by wrapping in another anonymous function.

doSomething('omg',(function(mark){
    return function(){
        console.log(mark);
    }
})('test'));

function doSomething(printthis,callback){
    console.log(printthis);
    callback();
}

jsfiddle

Upvotes: 0

Amadan
Amadan

Reputation: 198324

mark parameter would come from the call of callback(); however, you specify no parameters there, so mark will be undefined. If you wrote callback(printthis + " in callback"), then you would have received "omg in callback" in console.

// using document.write() so it shows up on the snippet. Don't do this at home. :)

doSomething('omg',function(mark){
    document.write("<p>" + mark + "</p>");
});

function doSomething(printthis,callback){
    document.write("<p>" + printthis + "</p>");
    callback(printthis + " in callback");
}

Upvotes: 2

Related Questions