JavaScript变量的作用域讲解

时间:2017-07-28
javascript中变量的作用范围是多大?它们与内部函数相同吗?如果定义全局变量,那么变量存储在哪里?本文章想大家详细介绍JavaScript变量的作用域,需要的朋友可以参考一下。

JavaScript只有两种变量:

  1. 全局变量:全局变量只不过是一个窗口级别的范围。
  2. 局部变量:在函数里定义的变量为局部变量,局部变量只在函数内有效。

全局变量:

全局变量正如全球明星(成龙,纳尔逊·曼德拉)。您可以从应用程序的任何部分访问它们(获取或设置值)。全局函数就像全球事件(新年,圣诞节)。您可以从应用程序的任何部分执行(调用)它们。

//global variable
var a = 2;

//global function
function b(){
   console.log(a);  //access global variable
}

局部变量:

如果你在美国,你可能会知道Kim Kardashian,臭名昭着的名人(她以某种方式设法制作小报)。但美国以外的人不会认出她。她是一个当地的明星,绑在她的领土上。

局部变量就像本地明星。您只能在本地范围内访问它们(获取或设置值)。本地函数就像本地事件 - 您可以在该范围内执行(庆祝)。如果要从范围外访问它们,您将收到错误信息。

function b(){
   var d = 21; //local variable
   console.log(d);

   function dog(){  console.log(a); }
     dog(); //execute local function
}

 console.log(d); //ReferenceError: dddddd is not defined  

JavaScript变量作用域示例:

1.全局变量

var a = 1;

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

2.局部变量

var a = 1;

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

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

3.中间变量

JavaScript中没有块范围

示例1:

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'

4.闭包中的变量作用范围

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'
  };
})();

5.基于原型的变量范围

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'

6.一个额外的复杂案例(局部变量和全局变量)

var x = 5;

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

以上示例打印出undefined10而不是510,因为x在函数中已经被重新定义了,以上代码等于:

var x = 5;

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

7.Catch子句变量作用域

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

将打印出来565。catch子句内部e隐藏全局变量和局部变量。但这个特殊的范围只适用于被捕获的变量。如果您var f;在catch子句中写入,那么它与在try-catch块之前或之后定义的完全相同。