Reputation: 2427
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
});
}
Upvotes: 1
Views: 147
Reputation: 32082
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.
Upvotes: 3
Reputation: 20878
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.
Upvotes: 0
Reputation: 14459
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.
Upvotes: 2
Reputation: 1077
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.
Upvotes: 0