I converted my CoffeeScript code to JavaScript using http://js2coffee.org
ResetControls = ->
$("#menu_item_url").val ""
$("#menu_item_name").val ""
$("#resource_id").prop "selectedIndex", 0
$("#resource_type_id").prop "selectedIndex", 0
It converted it to:
var ResetControls;
ResetControls = function() {
$("#menu_item_url").val("");
$("#menu_item_name").val("");
$("#resource_id").prop("selectedIndex", 0);
return $("#resource_type_id").prop("selectedIndex", 0);
};
The first line in the converted JavaScript code suggests that its some kind of a best practice to put var keyword before variable name, when assigning function to a variable. Is it so? How?
In my understanding, var
comes handy in recursive calls where your intention is to make copies of variables inside the recursive function (otherwise they will be shared or remain static between the recursive calls ).
Is there any other significance of var
?
Yes, you have to put var
before variable name. In this way you are declaring variable in the current scope - otherwise JS will search for it in outer scopes and if not declared in any scope - will make it global. As far as I know, in strict
mode, even global variables should be declared with var
in the global space.
PS This is valid for all variables, not only for those that you assign a function to
And another reason is garbage collection. Any variable created without the var keyword is created at the global scope and is never eligible for garbage collection, presenting the opportunity for a memory leak.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.