I’ve got a JavaScript object built like this:
var Dashboard = {
form: {
action: function(){
return $('#upload_form').attr('action');
}(),
//snip (more functions)
}
}
If I call (using Chrome 17 on WinXP) Dashboard.form.action in the Chrome console after the page loaded (I checked the script and the function is there) the result is undefined but, if I then redefine Dashboard.form.action using the same function:
Dashboard.form.action = function(){
return $('#upload_form').attr('action');
}();
and subsequently call it, it works as expected!
What am I doing wrong? Is this a bug or am I just overthinking it?
Update:
Re your comment below:
In the question you said:
which makes it seem like you’re expecting
actionto be a function (you don’t “call” non-functions).If you’re expecting it to be a string (the “action” attribute value from
#upload_form), then you don’t need to use a function at all. But you do need to be sure that you’re doing it after the#upload_formelement already exists in the DOM.To do that, either put your script below it in the markup (anywhere below it is fine; just before or just after the closing
</body>tag works well), or wrap your script in areadycall.So your code becomes either this if it’s after the
#upload_formin the markup:…or this if you want to use
ready(anything else usingDashboardwill have to wait untilreadyas well):Note that in the second case,
Dashboardwill no longer be a global variable. That’s a good thing, but if you need it to be global for some reason, you can export it:Just make sure nothing tries to use
Dashboardbeforereadyhas fired.Original answer:
You have an extra pair of
()on that:By putting them there, you call the function immediately, and assign the result of calling it to the
actionproperty. You just want to assign the function itself to the property, so don’t put the()at the end to call it:This is for exactly the same reason you wouldn’t use
()here (let’s assume you have a function calledfoo) if you wantfto refer tofoo:If you said
…you’d be calling
foo, not referring to it.