javascript中的var
·
在js中要特别注意,如果是旧代码,变量的定义是使用var,使用该关键字定义变量会有两种作用域,一种是全局作用域,一种是函数作用域
1、全局作用域
if (true) {
var test = true; // use "var" instead of "let"
}
alert(test); // true, the variable lives after if
2、函数作用域
function sayHi() {
if (true) {
var phrase = "Hello";
}
alert(phrase); // works
}
sayHi();
alert(phrase); // ReferenceError: phrase is not defined
3.变量提升
特别要注意的是var会导致变量提升,总是将变量定义提升到头部执行,但是赋值却是在对应的位置执行
function sayHi() {
alert(phrase);
var phrase = "Hello";
}
sayHi();
因为变量提升的原因,alert不好报错,但是会提示undefined
更多推荐



所有评论(0)