JavaScript 随手记-变量那些事

var 需要注意的一些细节

第一感受

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

值得注意的东西

  • 变量被重新声明时,它的值不变 If you re-declare a JavaScript variable, it will not lose its value.
var name = 'Bob'
console.log(name)
// expected output: Bob
var name
console.log(name)
// expected output: Bob
  • 已经声明但没有赋值的变量可以被删除 Undeclared variables are configurable (e.g. can be deleted).
var a = 1;
b = 2;

delete this.a; // Throws a TypeError in strict mode. Fails silently otherwise.
delete this.b;

console.log(a, b); // Throws a ReferenceError. 
// The 'b' property was deleted and no longer exists.
  • 未声明就直接赋值的变量都被视为全局变量 Undeclared variables are always global.
function x() {
  y = 1;   // Throws a ReferenceError in strict mode
  var z = 2;
}

x();

console.log(y); // logs "1" 
console.log(z); // Throws a ReferenceError: z is not defined outside x
  • 所有变量声明都会被率先执行 Declared variables are created before any code is executed. 这也叫变量提升 variable hoisting 这也意味着允许变量先使用再声明
bla = 2;
var bla;
// ...

// is implicitly understood as:

var bla;
bla = 2;
  • 关于变量的 hoisting 还需要注意,常见的 var a = 1; 的形式需要有意拆分为两部分执行,第一步是变量先声明 var a; 第二步是变量赋值 a = 1;

    尤其是两个变量同时声明并赋值的情况,如 var a = b = 1; 或者 var a = b, b = 1; 都要先执行 var a;var b;

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

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