문제

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.

P.S. 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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top