views:

58

answers:

4

I have a function like this

function saveProfile(data, url, successFn) {

    $.ajax({

        dataType: 'json',
        data: data,
        url: url,
        type: 'post',
        success: function () {
            successFn();
        }
    });
}

is there any difference to passing the successFn directly like this...

function saveProfile(data, url, successFn) {

    $.ajax({

        dataType: 'json',
        data: data,
        url: url,
        type: 'post',
        success: successFn
    });
}
A: 

The first version would let you perform some additional operations, before or after you execute successFn, but as it is currently written, there is no benefit, and the second version is much cleaner.

Also, this doesn't have anything to do with function objects.

mikerobi
A: 

To be clear, in the first example, you are wrapping the function successFn in another anonymous function, so you are in effect calling 2 functions. The second example, as others have stated, passes the function itself, and is correct for what you are doing.

James Connell
+2  A: 

If the only thing you want to do on success is call successFn(), then no, there isn't any practical difference between the two methods you describe. That said, I'd go with the latter since it's cleaner and quicker.

Chris
yeah sometimes javascript is a little funky, especially with closures and such. Just wanted to double check before i pushed it live.
wcpro
+3  A: 

The difference is that in the first example, successFn will not get the callback function arguments. Neither will the this object be the same; in fact, it will be window rather than whatever may be specified as the context for the .ajax() call if the function is not a member of an object (in xyz.successFn(), this would be xyz).

The first approach is less concise and possibly slower; by "wrapping" the function, you are quite possibly using more browser memory and CPU time. I wouldn't use the first approach unless you are paid by the line of code or you need this to point to an object that successFn is a member of.

idealmachine
Erm, surely you mean the first example rather than second? (Unless the question has been edited I suppose.)
bobince
@bobince: Fixed it.
idealmachine