简体   繁体   English

用var分配给变量的Javascript函数

[英]Javascript function assigned to variable with var

I converted my CoffeeScript code to JavaScript using http://js2coffee.org 我使用http://js2coffee.org将CoffeeScript代码转换为JavaScript

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. 转换后的JavaScript代码的第一行表明,在将函数分配给变量时,将var关键字放在变量名之前是一种最佳实践。 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 ). 以我的理解, var在递归调用中很方便,您的目的是在递归函数内复制变量(否则它们将在递归调用之间共享或保持静态)。

Is there any other significance of var ? var还有其他意义吗?

Yes, you have to put var before variable name. 是的,您必须将var放在变量名之前。 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. 这样,您可以在当前作用域中声明变量-否则JS将在外部作用域中搜索变量,如果未在任何作用域中声明-则将其设为全局变量。 As far as I know, in strict mode, even global variables should be declared with var in the global space. 据我所知,在strict模式下,即使全局变量也应在全局空间中用var声明。

PS This is valid for all variables, not only for those that you assign a function to PS这对所有变量均有效,不仅对分配了功能的变量有效。

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. 任何不带var关键字创建的变量都将在全局范围内创建,并且永远不会进行垃圾回收,这会导致内存泄漏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM