Javascript关注在已存在的变量上使用'var' [英] Javascript concerns of using 'var' on an already-existing variable

查看:123
本文介绍了Javascript关注在已存在的变量上使用'var'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在代码中为对象启动 var

Let's say I start up a var for an Object in my code

var base = {x:Infinity,y:Infinity};

以及之后我在同一范围内

and later in the same scope I do

var base = {x:0,y:0}

我知道我可以重复使用现有变量,但我正在尝试迭代某个点

I get that I can re-use the existing variable, but I'm trying to iterate on a point.


  1. 就内存而言,是否会导致当前范围出现任何问题?

  2. 如果这些问题存在差异,会不会有任何问题?范围?

  3. 一般规则是永远不要在现有变量上使用var吗?

  4. 如果我做了几次(数千次),我会遇到任何时髦的问题吗?

  1. Does this cause any problems for the current scope as far as memory is concerned?
  2. Would there be any problems if these are in different scopes?
  3. Is the general rule to never use var on an already-existing variable?
  4. If I did this several (thousands) of times, would I run into any "funky" issues?


推荐答案


  1. 它释放旧值,因此可能会被垃圾收集。我可能会说,因为对象可以被不同的变量引用。

  1. It releases its hold on the old value, so it can be potentially garbage collected. I say potentially, because objects can be referenced by different variables.

如果它们在不同的范围内,那么内部的基础将遮蔽外部的(假设您正在讨论嵌套作用域),因此旧值不会被覆盖。通常最好避免使用阴影。

If they're in different scopes, the inner base will shadow the outer one (assuming you're talking about nested scopes), so the old value will not be overwritten. Shadowing is usually best avoided.

通常,在相同的范围内,是的,但更多的是编码风格方面。它不会在执行中产生有效的差异,因为无论在同一范围内声明相同的 var 多少次,只有一个声明。

Generally, within the same scope, yes but that's more of a coding style aspect. It won't make an effective difference in the execution since there's only one declaration no matter how many times you declare the same var in the same scope.

取决于。你是在谈论在循环中覆盖?如果您不再需要当前值,则不应该是一个问题。

Depends. Are you talking about overwriting in a loop? If you no longer need the current value, it shouldn't be an issue.






要明白,当你这样做时:


To be clear, when you do this:

var base = {x:Infinity, y:Infinity};

var base = {x:0, y:0}

什么是真正发生的是:

var base;  // declaration is hoisted

base = {x:Infinity, y:Infinity};  // new object is referenced by base

base = {x:0, y:0}  // previous object is released, and new object is referenced






请注意,当我谈论范围和 var ,我在具体谈论功能范围。在标准的JavaScript / ECMAScript实现中,没有块作用域,因此在中使用 var 时没有特殊含义例如。


Note that when I talk about scope and var, I'm talking specifically about function scope. In standard JavaScript/ECMAScript implementations, there is no block scope, so there's no special meaning when using var in a for statement for example.

@Charles Bailey所述,Mozilla有 let ,它允许在块中进行作用域,但它需要特定的关键字。 var 语句无法识别与变量范围有关的块。

As mentioned by @Charles Bailey, Mozilla has let, which does allow scoping in blocks, but it would require that specific keyword. The var statement doesn't recognize the block with respect to variable scope.

这篇关于Javascript关注在已存在的变量上使用'var'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆