You're really close. Your hunch about the comma operator is correct. And I think there's a better way to wire up your done()
callback so that the code is a bit more robust, and the order in which things happen is a bit clearer.
First, let's look at the return
statement. All return statements do two things (evaluate the return value, then return it), but because of the comma, this one is doing three, in the following order:
- Evaluating the object literal
{ getI:... }
- evaluating
callback()
, which means calling callback()
- returning the return value of
callback()
, since the comma operator returns it's second operand.
So, note that callback()
actually gets called before your function returns, so it happens before dateFilter
has a value. (And, even if it did have a value, it would be the return value from callback()
, which is undefined.)
And I think there's another aspect of your code here that I think is worth a look. Callbacks typically take parameters. The simplest way to think of it is: Instead of returning a value, you pass it to the callback.
In general, code is easier to read and debug if you pass parameters instead of side-effecting shared variables.
I just made one change to your code, and it's working:
function done(dateFilter) {
console.log(dateFilter.getI());
console.log(dateFilter.getF());
}
(function(callback) {
var _dInicio = new Date(), _d = new Date(),
_dFim = new Date(_d.setMonth(new Date().getMonth() - 1));
callback({
getI: function() { return _dInicio; },
getF: function() { return _dFim; },
setI: function(d) { _dInicio = d; },
setF: function(d) { _dFim = d; }
});
})(done);
So, what did I do?
- Instead of side-effecting the
dateFilter
value, I pass it directly to callback
.
This means: no comma operator in the return
statement, and no need to side-effect the dateFilter
global value. (dateFilter
is now a parameter to done
isntead.)
I hope that clarifies things for you. Cheers!