Should I use var in the for in construct?

半世苍凉 提交于 2019-12-02 06:50:42

问题


I make use of a for in loop in a piece of JavaScript logic. Should I use the var keyword or not?

When I run a for-in loop as per W3School's example, without the var then, as a side effect, it gets defined as a property on the global scope (window):

(function () {

  var object = {
      a: 1,
      b: 2
  }
  for (varName in object) {
      alert(varName + " is" + object[varName])
  }

})();

alert(window.varName) //Returns "b" !
//This returns undefined when the for-in is rewritten as for (var varName in object).

edit: here is a fiddle of the above code for your enjoyment: http://jsfiddle.net/94uEh/

Which is the correct, preferred form? - Note that I wish to support IE 8 (EcmaScript < 5)


回答1:


You should always use var, if you want the value to be local.

Using the keyword object for a variable, is not recommended, you might run into undefined behavior across browsers.

Also you should generally avoid applying anything that is suppose to be local to the global scope.

This is bad:

for (varName in object) {
    alert(varName + " is" + object[varName])
}

This is correct:

for (var varName in object) {
    alert(varName + " is" + object[varName])
}

If you need to access this value in the global scope, you are probably doing it wrong. Also having this in the global scope is useless, as it will only be the last value, that will exist in the varName.




回答2:


You should always use var, otherwise you are accessing a global variable (and there's a risk you are overwriting someone's else variable)



来源:https://stackoverflow.com/questions/21377662/should-i-use-var-in-the-for-in-construct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!