最近打算学习下一些互联网的东西也就是vue+es6这些,笔记写在有道云上,不利于整理以及呈现。因此一步一步挪到博客上,另外也算是复习(预习)下吧。javascript
基本都是照抄就是了java
let 所声明的变量,只在 let 所在的代码块内有效。这样有个效果,循环时的的每一个let都是独立的git
eg:let经典的for循环es6
var a = []; for (var i = 0; i < 10; i++) { a[i] = function () { console.log(i); }; } a[6](); // 10 var a = []; for (let i = 0; i < 10; i++) { a[i] = function () { console.log(i); }; } a[6](); // 6
for
循环还有一个特别之处,就是设置循环变量的那部分是一个父做用域,而循环体内部是一个单独的子做用域。github
for (let i = 0; i < 3; i++) { let i = 'abc'; console.log(i); } // abc // abc // abc
这里就要注意循环变量在内部使用的时候,不要一当心赋值了。数组
var tmp = 123; if (true) { tmp = 'abc'; // ReferenceError let tmp; }
也就是用let定义的变量,在做用域定义的那就话以前是没办法用的,不够是否是在外面定义域中是否有定义。浏览器
typeof会报错。。未定义也就undefined数据结构
typeof x; // ReferenceError let x; typeof undeclared_variable // "undefined"
隐蔽的死区ide
function bar(x = y, y = 2) { return [x, y]; } bar(); // 报错 //另外 // 不报错 var x = x; // 报错 let x = x;
如题。
问题
内层变量可能会覆盖外层变量
var tmp = new Date(); function f() { console.log(tmp); if (false) { var tmp = 'hello world'; } } f(); // undefined
用来计数的循环变量泄露为全局变量。注意for循环var i = 0此时能够算在外层。
var s = 'hello'; for (var i = 0; i < s.length; i++) { console.log(s[i]); } console.log(i); // 5
// 浏览器的 ES6 环境 function f() { console.log('I am outside!'); } (function () { if (false) { // 重复声明一次函数f function f() { console.log('I am inside!'); } } f(); }()); // Uncaught TypeError: f is not a function
由于在ES6中的函数声明会有提高(let才没有提高)
// 浏览器的 ES6 环境 function f() { console.log('I am outside!'); } (function () { var f = undefined; if (false) { function f() { console.log('I am inside!'); } } f(); }()); // Uncaught TypeError: f is not a function
常量
简单来讲
ES6中的const
对于简单类型的数据(数值、字符串、布尔值),值就保存在变量指向的那个内存地址,所以等同于常量。
对于复合类型的数据(主要是对象和数组),变量指向的内存地址,保存的只是一个指针,const
只能保证这个指针是固定的,至于它指向的数据结构是否是可变的,就彻底不能控制了。
const foo = {}; // 为 foo 添加一个属性,能够成功 foo.prop = 123; foo.prop // 123 // 将 foo 指向另外一个对象,就会报错 foo = {}; // TypeError: "foo" is read-only
引入global
做为顶层对象。也就是说,在全部环境下,global
都是存在的,均可以从它拿到顶层对象。
垫片库system.global
模拟了这个提案,能够在全部环境拿到global
。
// CommonJS 的写法 require('system.global/shim')(); // ES6 模块的写法 import shim from 'system.global/shim'; shim();
上面代码能够保证各类环境里面,global
对象都是存在的。
// CommonJS 的写法 var global = require('system.global')(); // ES6 模块的写法 import getGlobal from 'system.global'; const global = getGlobal();