JavaScript 随手记-变量那些事

第一感受

我的第一感受当然是有种 Python 的感觉了,蟒蛇感。。。

值得注意的东西

变量被重新声明时,它的值不变 If you re-declare a JavaScript variable, it will not lose its value.

1var name = 'Bob'
2console.log(name)
3// expected output: Bob
4var name
5console.log(name)
6// expected output: Bob

已经声明但没有赋值的变量可以被删除 Undeclared variables are configurable (e.g. can be deleted).

1var a = 1;
2b = 2;
3
4delete this.a; // Throws a TypeError in strict mode. Fails silently otherwise.
5delete this.b;
6
7console.log(a, b); // Throws a ReferenceError. 
8// The 'b' property was deleted and no longer exists.

未声明就直接赋值的变量都被视为全局变量 Undeclared variables are always global.

1function x() {
2  y = 1;   // Throws a ReferenceError in strict mode
3  var z = 2;
4}
5
6x();
7
8console.log(y); // logs "1" 
9console.log(z); // Throws a ReferenceError: z is not defined outside x

所有变量声明都会被率先执行 Declared variables are created before any code is executed. 这也叫变量提升 variable hoisting 这也意味着允许变量先使用再声明

1bla = 2;
2var bla;
3// ...
4
5// is implicitly understood as:
6
7var bla;
8bla = 2;

关于变量的 hoisting 还需要注意,常见的 var a = 1; 的形式需要有意拆分为两部分执行,第一步是变量先声明 var a; 第二步是变量赋值 a = 1;
尤其是两个变量同时声明并赋值的情况,如 var a = b = 1; 或者 var a = b, b = 1; 都要先执行 var a; 和 var b;

1var d = e, e = 1;
2console.log(d, e)
3// expected output: undefined 1
4var x = y, y = 'a';
5console.log(x+y)
6// expected output: undefineda

主要参考来源:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var

留下评论

您的电子邮箱地址不会被公开。 必填项已用*标注