javascript ES6简介 - 比较Var - to Let和Const

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript ES6简介 - 比较Var - to Let和Const相关的知识,希望对你有一定的参考价值。


//////////////////////////////////////////////////////////////////////////////
// var is hoisted to the top of the function, regardless of block
function varTest1 () {
  var x = 1;
  if (true) {
    var x = 2; // 'x' is the same variable as above
    console.log(x); // 2
  }
  console.log(x); // 2
}

function varTest2 () {
  console.log(a); // logs "undefined", but code still runs.
  var a = 2;
}

//////////////////////////////////////////////////////////////////////////////
// let` or `const` are scoped to the "block", not the function:
function letTest1 () {
  let x = 1;
  if (true) {
    let x = 2;  // different variable from above
    console.log(x); // 2
  }
  console.log(x); // 1 ==> this access ONLY the x defined in the let at the top of the full (function) block.
}

// won't allow reference before definition
function letTest2 () {
  console.log(b); // Reference ERROR!!!!: b is not defined. code stops execution ==> LET ONLY work in ORDER and, each time, create a NEW (variable) INSTANCE!!!
  let b = 3;
}

// When it comes to block scoping, let and const behave the same way

以上是关于javascript ES6简介 - 比较Var - to Let和Const的主要内容,如果未能解决你的问题,请参考以下文章

ES6 常用总结——第一章(简介letconst)

webpack-模块简介

JavaScript-ES6新特性

ES6上

Javascript学习笔记

ES6入门