I would like a function ‘get’ that takes an id, an optional property parameter and a callback function. It would be used like so:
get(14297, 'name', function processName(name) {...});
get(14297, function processStudent(student) {...});
I have included one possible implementation below
function get(id, property, callback) {
var item = ...;
// property is callback
if (!callback) property(item);
// callback is callback
else callback(item[property])
}
It feels a little bit weird because
property(item);
Is actually a callback function depending on the context. Is there a better way to do this?
You can change the order of parameters, or test what the function is given to work out what they are. e.g.
or
and so on, but that type of overloading is not particularly liked.