zno2

Re-Declaring JavaScript Variables

If you re-declare a JavaScript variable, it will not lose its value.

https://www.w3schools.com/js/js_variables.asp

var a = a || '123';

上面这个例子,如果之前a被声明过,且赋值了,则保留原值。如果没有被声明过,则初始化。

1. 报错

console.dir(a);

Uncaught ReferenceError: a is not defined

2. 输出 undefined

console.dir(a);
var a = 1;

undefined

3. 输出 1

var a = 1;
console.dir(a);

1

解释1:优先使用 local scope ,其次使用 global scope ,如果所有scope均没有,则报错。

解释2:声明在本域无序,赋值有序。

4. 输出 undefined

var a = 1;
var f = function(){
    console.dir(a);
    var a = 2;
}

undefined

5. 输出 1

var a = 1;
var f = function(){
    console.dir(a);
    a = 2;
}

1

 

posted on 2023-06-06 13:20  zno2  阅读(2)  评论(0编辑  收藏  举报

导航