动态ip可以做网站,北京万户网络,电子商务网站运营与...,小企业网站建设怎样可以快速发布自Kindem的博客#xff0c;欢迎大家转载#xff0c;但是要注意注明出处。另外#xff0c;该文章收纳在Kindem的个人的 IT 知识整理仓库#xff0c;欢迎 Star、Fork、投稿 let let是在ES6加入的新的变量声明方法#xff0c;let声明变量的方法和var类似: let a hello;
… 发布自Kindem的博客欢迎大家转载但是要注意注明出处。另外该文章收纳在Kindem的个人的 IT 知识整理仓库欢迎 Star、Fork、投稿 let let是在ES6加入的新的变量声明方法let声明变量的方法和var类似: let a hello;
var b hello;
复制代码let的功能是声明一个作用域被限制在块级的变量而var声明的变量的作用域只能是全局的或者整个函数块的 function varTest() {var x 1;if (true) {var x 2;// 2console.log(x);}// 2console.log(x);
}function letTest() {let x 1;if (true) {let x 2;// 2console.log(x);}// 1console.log(x);
}
复制代码再举一个例子: var a 1;
var b 2;if (a 1) {var a 11;let b 22;// 11console.log(a);// 22console.log(b);
}// 11
console.log(a);
// 2
console.log(b);
复制代码另外如果作用域位于程序的顶层var会挂载到window上而let不会: var a a;
let b b;// this - window
// a
console.log(this.a);
// undefined
console.log(this.b);
// a
console.log(window.a);
// undefined
console.log(window.b);
复制代码在相同的函数或块作用域内重新声明同一个变量会引发一个重复定义的SyntaxError if (x) {let foo;// SyntaxErrorlet foo;
}
复制代码let和var都会在声明所在的作用域顶部被创建这被称为变量提升但是不同的是var的创建会伴随着一个undefined值在赋值之后才会改变而let没有被赋值之前是不会被初始化的如果在这期间引用let声明的变量会导致一个ReferenceError直到初始化之前该变量都处于暂存死区: function test() {// undefinedconsole.log(bar);// ReferenceErrorconsole.log(foo);var bar 1;let foo 2;
}
test();
复制代码两个复杂一点的例子: function test(){var foo 33;if (true) {// ReferenceErrorlet foo (foo 55);}
}
test();
复制代码function go(n) {// Object {a: [1,2,3]}console.log(n);// ReferenceErrorfor (let n of n.a) {console.log(n);}
}
go({a: [1, 2, 3]});
复制代码const const的基本作用是声明一个作用域被限制在块级的常量其作用域和let一样基本使用也和let类似但是const的特点是const声明的值一经创建无法被改变 使用const会创建一个值的只读引用这意味着const声明的对象本省的引用是无法被改变的但是其属性是可以被改变的因为改变其属性并不会引起其引用的变化 下面给出const的一些特性的例子: 基本使用: const a abc;
复制代码无法被重复定义: const a abc;
// SyntaxError: Identifier a has already been declared
const a abc;
复制代码声明时就必须赋值: // SyntaxError: Missing initializer in const declaration
const a;
复制代码无法被修改: const a a;
// TypeError: Assignment to constant variable
a b;
复制代码块级作用域: if (true) {var a a;const b b;// aconsole.log(a);// bconsole.log(b);
}
// a
console.log(a);
// ReferenceError: not defined
console.log(b);
复制代码作用域在程序顶层时不会挂在window对象上: var a a;
const b b;// this - window
// a
console.log(this.a);
// undefined
console.log(this.b);
// a
console.log(window.a);
// undefined
console.log(window.b);
复制代码转载于:https://juejin.im/post/5b991742f265da0abe26e4bd