user2251919
user2251919

Reputation: 675

Passing in a function to another function?

Is it better practice to pass in a function to another function that uses it to reduce the scope look up. I am getting quite confused about this stuff.

Without passing it in;

function loadSuccess(a, b, c) {

};

function image(url, name, info) {

   var asset = new Image();
   asset.addEventListener("load", function(name, info) {
       return function() {
           loadSuccess(this, name, info);
       };
   }(name, info), false);
   asset.src = url;
};

image(a, b, c);

And passing it in;

function loadSuccess(a, b, c) {

};

function image(url, name, info, loadSuccess) {

   var asset = new Image();
   asset.addEventListener("load", function(name, info, func) {
       return function() {
           func(this, name, info);
       };
   }(name, info, loadSuccess), false);
   asset.src = url;
};

image(a, b, c, loadSuccess);

Upvotes: 2

Views: 123

Answers (3)

bfavaretto
bfavaretto

Reputation: 71908

The performance benefit is probably neglegible, but passing the callback makes your function more flexible, allowing you to pass a different callback in an different situation, if needed.

However, I see a problem in your code: tt makes no sense to return anything from an asynchronous callback. It's not your image function that will be returning it, but the inner anonymous function you passed to addEventListener.

Considering those problems, I'd change the code as follows:

function loadSuccess(a, b, c) {

};

function image(url, name, info, func) {
   var asset = new Image();
   asset.addEventListener("load", function(e) {
       func(this, name, info);
   }, false);
   asset.src = url;
};

image(a, b, c, loadSuccess);

I also removed the immediately invoked function you had, as I don't see any good reason to use it there.

Upvotes: 3

Damien
Damien

Reputation: 8987

The first option is to use when the image function always needs call this loadSucces function.

The second option is to use when you need to choose which callback function you want to execute.

There is also third option in which the fourth parameter is optionnal :

function image(url, name, info, loadSuccessParameter) {
    loadSuccessParameter= loadSuccessParameter || loadSuccess;
    [...]

}

So you can call this way : image(a, b, c) or this way : image(a, b, c, otherLoadSuccess);

I hope it helps.

Upvotes: 0

Dennis Traub
Dennis Traub

Reputation: 51634

Both works fine but I think it is good practice to send a callback function as an argument.

Upvotes: 1

Related Questions