首先要注意let是es6中的东西,起码是ie10之前的ie浏览器兼容要千万当心!嗯...然后我们来看javascript中用let语句声明作用域的用法讲解
语法
let variable1 = value1
参数variable1
要声明的变量的名称。
value1
赋给变量的初始值。
备注使用 let 语句声明一个变量,该变量的范围限于声明它的块中。 可以在声明变量时为变量赋值,也可以稍后在脚本中给变量赋值。
使用 let 声明的变量,在声明前无法使用,否则将会导致错误。
如果未在 let 语句中初始化您的变量,则将自动为其分配 javascript 值 undefined。
示例:
var l = 10;
{
let l = 2;
// at this point, l = 2.
}
// at this point, l = 10.
// additional ways to declare a variable using let.
let index;
let name = "thomas jefferson";
let answer = 42, counter, numpages = 10;
let myarray = new array();
块级作用域
for(var i = 0; i < 10; i++){}
console.log(i); //10
for(let j = 0; j < 10; j++){}
console.log(j); //"referenceerror: j is not defined
不存在变量提升
console.log(a); // 输出undefined
console.log(b); // 报错referenceerror
console.log(c); // 报错referenceerror
var a = 2;
let b = 2;
注意区别undefined和referenceerror
暂时性死区(tdz)只要进入当前块级作用域,所使用的变量已经存在了,但在声明之前都属于死区,不可进行操作。
注意: typeof不再是100%安全的操作
typeof x; // referenceerror
typeof y // undefined
let x;
不允许重复声明
let x = 1;
let x; // "syntaxerror: identifier 'x' has already been declared
var y = 2;
var y = 3; // y = 3
块级作用域
// 匿名函数写法
(function () {
var tmp = ...;
...
}());
// 块级作用域写法
{
let tmp = ...;
...
}
es5的严格模式规定,函数只能在顶层作用域和函数内声明,其他情况(比如if代码块、循环代码块)的声明都会报错。
// es5
'use strict';
if (true) {
function f() {} // 报错
}
es6由于引入了块级作用域,这种情况可以理解成函数在块级作用域内声明,因此不报错,但是构成区块的大括号不能少
// 报错
'use strict';
if (true)
function f() {}
声明的全局变量不再是window的属性
"use strict";
var a = 1;
console.log(window.a) // 1
let b = 1;
console.log(window.b) // undefined
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
对javascript function函数深入理解与实战(附上代码)
javascript基础心法(图文教程,详细为你解答)
有关javascript模块详细解答
以上就是javascript中用let语句声明作用域(图文教程)的详细内容。