JavaScript中的变量范围是什么?


JavaScript中的变量范围是什么?


全局范围的变量

// global scope
var a = 1;

function one() {
  alert(a); // alerts '1'
}

本地范围

// global scope
var a = 1;

function two(a) { // passing (a) makes it local scope
  alert(a); // alerts the given argument, not the global value of '1'
}

// local scope again
function three() {
  var a = 3;
  alert(a); // alerts '3'
}

中级:没有JavaScript中的块范围(ES5; ES6介绍let)

var a = 1;

function four() {
  if (true) {
    var a = 4;
  }

  alert(a); // alerts '4', not the global value of '1'
}

var a = 1;

function one() {
  if (true) {
    let a = 4;
  }

  alert(a); // alerts '1' because the 'let' keyword uses block scoping
}

中级:对象属性

var a = 1;

function Five() {
  this.a = 5;
}

alert(new Five().a); // alerts '5'

高级:闭包

var a = 1;

var six = (function() {
  var a = 6;

  return function() {
    // JavaScript "closure" means I have access to 'a' in here,
    // because it is defined in the function in which I was defined.
    alert(a); // alerts '6'
  };
})();

高级:基于原型的范围解析

var a = 1;

function seven() {
  this.a = 7;
}

// [object].prototype.property loses to
// [object].property in the lookup chain. For example...

// Won't get reached, because 'a' is set in the constructor above.
seven.prototype.a = -1;

// Will get reached, even though 'b' is NOT set in the constructor.
seven.prototype.b = 8;

alert(new seven().a); // alerts '7'
alert(new seven().b); // alerts '8'

全球+本地:一个额外复杂的案例

var x = 5;

(function () {
    console.log(x);
    var x = 10;
    console.log(x);
})();

这将打印出undefined和10而不是5和10自JavaScript的始终移动变量声明(未初始化)的范围的顶部,使得代码等同于:

var x = 5;

(function () {
    var x;
    console.log(x);
    x = 10;
    console.log(x);
})();

catch子句范围的变量

var e = 5;
console.log(e);
try {
    throw 6;
} catch (e) {
    console.log(e);
}
console.log(e);

这将打印出来5,6,5。在catch子句中e隐藏全局变量和局部变量。但是这个特殊范围仅适用于捕获的变量。如果你var f;在catch子句中写入,那么它就像你在try-catch块之前或之后定义它一样。