码迷,mamicode.com
首页 > Web开发 > 详细

js中let和var定义变量的区别

时间:2017-04-25 13:22:41      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:javascrip   class   nbsp   hello   console   方法   tle   com   cee   

javascript 严格模式

第一次接触let关键字,有一个要非常非常要注意的概念就是”JavaScript 严格模式”,比如下述的代码运行就会报错:

let hello = ‘hello world.‘;
console.log(hello);
  • 1
  • 2
  • 1
  • 2

错误信息如下:

let hello = ‘hello world.‘;
^^^

SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
    ...
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

解决方法就是,在文件头添加”javascript 严格模式”声明:

‘use strict‘;

let hello = ‘hello world.‘;
console.log(hello);
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

更多更详细的关于”javascript 严格模式”说明,请参考阮一峰的博客 
《Javascript 严格模式详解》

let和var关键字的异同

声明后未赋值,表现相同

‘use strict‘;

(function() {
  var varTest;
  let letTest;
  console.log(varTest); //输出undefined
  console.log(letTest); //输出undefined
}());
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

使用未声明的变量,表现不同:

(function() {
  console.log(varTest); //输出undefined(注意要注释掉下面一行才能运行)
  console.log(letTest); //直接报错:ReferenceError: letTest is not defined

  var varTest = ‘test var OK.‘;
  let letTest = ‘test let OK.‘;
}());
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

重复声明同一个变量时,表现不同:

‘use strict‘;

(function() {
  var varTest = ‘test var OK.‘;
  let letTest = ‘test let OK.‘;

  var varTest = ‘varTest changed.‘;
  let letTest = ‘letTest changed.‘; //直接报错:SyntaxError: Identifier ‘letTest‘ has already been declared

  console.log(varTest); //输出varTest changed.(注意要注释掉上面letTest变量的重复声明才能运行)
  console.log(letTest);
}());
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

变量作用范围,表现不同

‘use strict‘;

(function() {
  var varTest = ‘test var OK.‘;
  let letTest = ‘test let OK.‘;

  {
    var varTest = ‘varTest changed.‘;
    let letTest = ‘letTest changed.‘;
  }

  console.log(varTest); //输出"varTest changed.",内部"{}"中声明的varTest变量覆盖外部的letTest声明
  console.log(letTest); //输出"test let OK.",内部"{}"中声明的letTest和外部的letTest不是同一个变量
}());

js中let和var定义变量的区别

标签:javascrip   class   nbsp   hello   console   方法   tle   com   cee   

原文地址:http://www.cnblogs.com/ExMan/p/6761083.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!