在node中运行:

>function x(){a = 1}
undefined
> a
Thrown:
ReferenceError: a is not defined
> x()
undefined
> a
1

可以发现, 不加var的话, 运行一个函数内部的赋值, 这个值居然就变成全局变量!

> function y(){var b = 1}
undefined
> b
Thrown:
ReferenceError: b is not defined
> y()
undefined
> b
Thrown:
ReferenceError: b is not defined

加了var的话,就会把变量作用域限制在函数体内.

标签: none 阅读量: 1374

添加新评论