ES6 学习笔记

Let 命令声明变量 - 只在let命令所在的代码块内有效。

ex:

{

let a = 10;

var b = 21;

}

a   // 报错 ReferenceError: a is not defined

b

 

ex:

var ar = [];

for(var i=0; i<10; i++){

  var ix = i;

  ar[ix] = function(){

    console.log(ix);

  };

}

ar[6]();  // 9     变量提升

 

for(var y=0;y<10;y++){

  let num = y;

  ar[y] = function(){

    console.log(num);

  }

}

ar[6]();  // 6

 

Let 不允许在相同作用域内,重复声明同一个变量。

ex:

{

let a = 10;    //  TypeError: redeclaration of let a

 

var a = 10;

}

 

{

let a = 10;   //  TypeError: redeclaration of let a

let a = 20;

}

 

块级作用域

Let 实际上为Javascript新增了块级作用域

ex:

function block(){

  let num =1;

  if(true){

    let num = 2

  }

  console.log(num)         // 1  如果是var 输出为 2.

}

block()

 

ES6规定,函数本身的作用域,在其所在的块级作用域之内。

function fir(){

  console.log('outside')

}

(function sed(){

  if(false){

    function fir(){

      console.log('inside')

    }

  }

  fir();

}());

在ES5中,得到 inside ,在ES6中得到 outside。

 

Const 命令

const用来声明常量。一旦声明,其值就不能改变。

ex:

const PI = 3.1415926;

PI = 666   // SyntaxError: invalid assignment to const PI

 

 

const的作用域与let命令相同,只在声明所在的块级作用域内有效。

ex:

if(true){

const Max = 5;

}

// Max在此处不可得。ReferenceError: Max is not defined

 

 

const声明的常量,也与let一样不可重复声明。

ex:

var news = 'new one';

let age =  26;

// 以下两行都会报错

const news = 'new two';  // TypeError: redeclaration of var news

 

 

const age = 30;               // TypeError: redeclaration of var age

 

 

j

 

 

 

 

 

 

 

原文地址:https://www.cnblogs.com/papajia/p/4498214.html