Chances are that your code does not work because the value of this
is not what you expect it to be so thus this.startDate
does not change the variable startDate
you have in your code and thus that variable was never initialized.
You are misusing this
in that reference so that is the place to start in fixing your code. In fact, if you ran your code in strict
mode, your code would generate an error because this
would be undefined
. strict
mode is designed explicitly to prevent poor coding practices such as accidentally using this
the wrong way.
Why is this.startDate
a poor construction, what's a better construction?
this
is used to refer to an object inside a method call as in obj.method()
. Inside of method
, this
will refer to obj
or this
can be used in a few other circumstances when the caller of a function explicitly causes the value of this
to be set to a meaningful value. In a normal function call, this
will either be the global object or in strict mode will be undefined
and should generally not be used. See this answer for a listing of exactly what situations the value of this
is set to something unique.
Inside a normal function call where this
is not explicitly set for you by the caller, you should not be using this
at all. In fact, if you run your code in strict mode (which is highly recommended), the value of this
will be undefined
in your init
function.
If you're just trying to set the higher level scoped variable named startDate
to the value of whatever was passed to init
, then you should change your argument name to the init
function to a non-conflicting name and then just refer directly to the startDate
variable like this:
var startDate;
var init = function(initialDate) {
startDate = initialDate;
logStartDate();
};
var logStartDate = function() {
console.log(startDate);
};
init('2015-01-02');
Isn't a function expression a closure?
A closure is only created under certain circumstances when some sort of internal reference inside a function is lasting which keeps the scope of the function alive after it finishes executing. All function expressions are not closures. You do not have a closure in this code. See How do JavaScript closures work? for much more discussion of closures.