Javascript method parameter ordering
I have a Javascript method that's called deleteObjectsDependingOnX(objects, X), is it conventional to have the order of parameters as objects first and then X, or the reverse?
This is more a question on what the convention is in Javascript开发者_开发技巧. I believe, in C++, the convention is to do the reverse, but wasn't sure what people do in Javascript.
I think there are no conventions about such things in JavaScript.
If X
is a callback function, then putting it last seems more common and leads to (IMHO) easier to read code like this:
deleteObjectsDependingOnX(objects, function(o) {
// return true if o should die, false otherwise
});
The "callback at the end" is pretty common jQuery, see $.each
and $.grep
for examples.
Of course, setTimeout
puts the arguments in the other order so the time value can get lost:
setTimeout(function() {
// Do a bunch of stuff and things.
}, 500);
OTOH, if you use a named function rather than an anonymous one, it looks okay:
setTimeout(doStuffAndThings, 500);
So I think the real answer is "it depends". If you're expecting anonymous functions more often than named ones, then putting the callback at the end will make for (IMHO) easier to read code.
精彩评论