Home > Web Front-end > JS Tutorial > body text

Javascript变量作用域详解_javascript技巧

WBOY
Release: 2016-05-16 17:10:26
Original
1043 people have browsed it

变量的作用域指的是变量的可见性,而生命周期则(存活期)则是从另一个角度考察变量。

JS中变量的作用域分为全局变量和局部变量,函数内定义的称为局部变量,函数外的称为全局变量。(“函数外的称为全局变量”是相对的,另此处讨论的前提是用var显式声明的变量,函数内不用var定义的变量默认是全局变量,当然忽略var声明变量是不赞成的)。

复制代码 代码如下:

var glob = 4;//函数外声明全局变量
function fun() {
    var height = 20; //函数内用var声明的是局部变量
    weight = 50; //函数内不用var声明的是全局变量
}
fun();
alert(weight);

JS中没有块级作用域,即用大括号{}包含的。Java中则有。在main方法中写入下代码
复制代码 代码如下:

public static void main(String... args) {
  for(int i=0;i  }
    {
        int j=10;
    }
    int z = 20;
    System.out.println(i); // i不可见,语法分析时报错,即编译不通过
    System.out.println(j); // j不可见,语法分析时报错,即编译不通过
    System.out.println(z); // z可见,输出20
}

但如果在JS中
复制代码 代码如下:

for(var i=0;i}
var obj = {name:"Lily"};
for(var attr in obj) {
}
{
  var j=10;
}
alert(i);//输出4,没有块级作用域
alert(attr); //输出name,没有块级作用域
alert(j);//输出10,没有块级作用域

这也说明一个问题,避免在全局范围内使用for循环同时声明变量,否则会造成全局命名范围的污染。

当然,JS1.7中提出了let关键字声明变量(见https://developer.mozilla.org/cn/New_in_JavaScript_1.7),只作用于for语句范围。

复制代码 代码如下:

for(let i=0;i   //todo
}
alert(i);//运行时报错,提示i未定义

JS1.7需要这样引用

ps:firefox2+实现了JS1.7

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!