ECMAScript是JavaScript的规范、标准,ECMAScript由ECMA制定,JavaScript由Netscape 公司创造。
ES6 是一个泛指,含义是 5.1 版以后的 JavaScript 的下一代标准,涵盖了 ES2015、ES2016、ES2017 等等。
Babel 是一个广泛使用的 ES6 转码器,可以将 ES6 代码转为 ES5 代码,让使用ES6时不用担心现有环境是否支持。
// 转码前
input.map(item => item + 1);
// 转码后
input.map(function (item) {
return item + 1;
});
`1.let与var类似,但变量只在声明代码块内有效`
//var
var a = [];
for (var i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
};
}
a[6](); // 10
//let
var a = [];
for (let i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
};
}
a[6](); // 6
`**for循环有一个特别之处,就是设置循环变量的那部分是一个父作用域,而循环体内部是一个单独的子作用域`
for (let i = 0; i < 3; i++) {
let i = 'abc';
console.log(i);
}
// abc
// abc
// abc
`2.let不存在变量提升(即变量可以在声明之前使用)而var存在`
// var 的情况
console.log(foo); // 输出undefined
var foo = 2;
// let 的情况
console.log(bar); // 报错ReferenceError
let bar = 2;
`3.暂时性死区: 在代码块内,使用let命令声明变量之前,该变量都是不可用的。`
function bar(x = y, y = 2) {
return [x, y];
}
bar();// 报错 y没有声明,交换两个参数位置。
//**typeof的不安全性
typeof x; // ReferenceError
let x;
//如果变量未声明 typeof反而不报错
typeof undeclared_variable // "undefined"
`4.不允许重复声明`
// 报错
function func() {
let a = 10;
let a = 1;
}
// 浏览器的 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 环境
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
//**考虑到环境导致的行为差异太大,应该避免在块级作用域内声明函数。如果确实需要,也应该写成函数表达式,而不是函数声明语句。
// 块级作用域内部的函数声明语句,建议不要使用
{
let a = 'secret';
function f() {
return a;
}
}
// 块级作用域内部,优先使用函数表达式
{
let a = 'secret';
let f = function () {
return a;
};
}
//**ES6 的块级作用域必须有大括号
// 第一种写法,报错
if (true) let x = 1;
// 第二种写法,不报错
if (true) {
let x = 1;
}
const声明一个只读的常量。一旦声明,常量的值就不能改变。并且必须立即初始化。
其他与let一致:在块级作用域内有效、变量不提升、存在暂时性死区、不可重复声明。
const PI = 3.1415;
PI // 3.1415
PI = 3;
// TypeError: Assignment to constant variable.
//立即初始化
const foo;
// SyntaxError: Missing initializer in const declaration
const实际上保证的,并不是变量的值不得改动,而是变量指向的那个内存地址所保存的数据不得改动。
顶层对象,在浏览器环境指的是window对象,在 Node 指的是global对象。ES5 之中,顶层对象的属性与全局变量是等价的。
从 ES6 开始,全局变量将逐步与顶层对象的属性脱钩。
var a = 1;
// 如果在 Node 的 REPL 环境,可以写成 global.a
// 或者采用通用方法,写成 this.a
window.a // 1
let b = 1;
window.b // undefined
ES2020 在语言标准的层面,引入globalThis作为顶层对象,在任何环境下,globalThis都是存在的,都可以从它拿到顶层对象,指向全局环境下的this。
//set结构也可以使用数组的解构赋值
let [x, y, z] = new Set(['a', 'b', 'c']);
x // "a"
//事实上,只要某种数据结构具有 Iterator 接口,都可以采用数组形式的解构赋值。
function* fibs() {
let a = 0;
let b = 1;
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
let [first, second, third, fourth, fifth, sixth] = fibs();
sixth // 5
let [foo = true] = [];
foo // true
let [x, y = 'b'] = ['a']; // x='a', y='b'
let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'
//ES6 内部使用严格相等运算符(===),判断一个位置是否有值。只有当一个数组成员严格等于undefined,默认值才会生效。
let [x = 1] = [null];
x // null
let [x = 1, y = x] = [1, 2]; // x=1; y=2
let [x = y, y = 1] = []; // ReferenceError: y is not defined
`1.对象的属性没有次序,变量必须与属性同名,才能取到正确的值。`
let { foo, bar } = { foo: 'aaa', bar: 'bbb' };
//相当于 let { foo:foo, bar:bar } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa"
bar // "bbb"
let {baz}={foo:"aaa",bar:"bbb"}
baz//undefined
`2.对象的解构赋值的内部机制,是先找到同名属性,然后再赋给对应的变量。
foo是匹配的模式,baz才是变量。真正被赋值的是变量baz,而不是模式foo。`
var {foo:baz}={foo:"aaa",bar:"bbb"}
baz//"aaa"
foo // error: foo is not defined
let baz;
let {bar:baz}={bar:1}//SyntaxError:Duplicate declaration "baz"
`3.上面代码中,解构赋值的变量都会重新声明,所以报错了。
不过,因为var命令允许重新声明,所以这个错误只会在使用let和const命令时出现。
如果没有第二个let命令,上面的代码就不会报错。`
let foo;
({foo}={foo:1});//成功
let baz;
({bar:baz}={bar:1})//成功
`4.下面只有line是变量,loc和start都是模式,不是变量`
const node = {
loc: {
start: {
line: 1,
column: 5
}
}
};
let { loc, loc: { start }, loc: { start: { line }} } = node;
line // 1
loc // Object {start: Object}
start // Object {line: 1, column: 5}
`5.Object.setPrototypeOf() 赋原型`
const obj1 = {};
const obj2 = { foo: 'bar' };
Object.setPrototypeOf(obj1, obj2);
const { foo } = obj1;
foo // "bar"
`6.对象解构的默认值`
var {x: y = 3} = {};
y // 3
var {x: y = 3} = {x: 5};
y // 5
//默认值生效的条件是,对象的属性值严格等于undefined。
`1.[]`
const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"
`2.数组对象有length属性 {}`
let {length : len} = 'hello';
len // 5
`1.解构赋值的规则是,只要等号右边的值不是对象或数组,就先将其转为对象。由于undefined和null无法转为对象,所以对它们进行解构赋值,都会报错。`
let {toString: s} = 123;
s === Number.prototype.toString // true
let {toString: s} = true;
s === Boolean.prototype.toString // true
let { prop: x } = undefined; // TypeError
let { prop: y } = null; // TypeError
function move({x = 0, y = 0} = {}) {
return [x, y];
}
move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, 0]
move({}); // [0, 0]
move(); // [0, 0]
function move({x, y} = { x: 0, y: 0 }) {
return [x, y];
}
move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, undefined]
move({}); // [undefined, undefined]
move(); // [0, 0]
[[1, 2], [3, 4]].map(([a, b]) => a + b);
// [ 3, 7 ]
[1, undefined, 3].map((x = 'yes') => x);
// [ 1, 'yes', 3 ]
`变量声明语句,模式不能使用圆括号。`
// 全部报错
let [(a)] = [1];
let {x: (c)} = {};
let ({x: c}) = {};
let {(x: c)} = {};
let {(x): c} = {};
let { o: ({ p: p }) } = { o: { p: 2 } };
`赋值语句的非模式部分,可以使用圆括号。`
[(b)] = [3]; // 正确
({ p: (d) } = {}); // 正确
[(parseInt.prop)] = [3]; // 正确
`1.交换变量的值`
let x = 1;
let y = 2;
[x, y] = [y, x];
`2.从函数返回多个值`
// 返回一个数组
function example() {
return [1, 2, 3];
}
let [a, b, c] = example();
// 返回一个对象
function example() {
return {
foo: 1,
bar: 2
};
}
let { foo, bar } = example();
`3.函数参数的定义`
// 参数是一组无次序的值
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});
`4.提取 JSON 数据`
let jsonData = {
id: 42,
status: "OK",
data: [867, 5309]
};
let { id, status, data: number } = jsonData;
console.log(id, status, number); // 42, "OK", [867, 5309]
`5.函数参数的默认值`
jQuery.ajax = function (url, {
async = true,
beforeSend = function () {},
cache = true,
complete = function () {},
crossDomain = false,
global = true,
// ... more config
} = {}) {
// ... do stuff
};
`6.遍历 Map 结构`
const map = new Map();
map.set('first', 'hello');
map.set('second', 'world');
for (let [key, value] of map) {
console.log(key + " is " + value); // first is hello second is world
}
//只获取键值
// 获取键名
for (let [key] of map) {
// ...
}
// 获取键值
for (let [,value] of map) {
// ...
}
`7.输入模块的指定方法`
const { SourceMapConsumer, SourceNode } = require("source-map");
ES6 为字符串添加了遍历器接口,使得字符串可以被for…of循环遍历。
for (let codePoint of 'foo') {
console.log(codePoint) // "f" "o" "o"
}
模板字符串(template string)是增强版的字符串,用反引号(`)标识。它可以当作普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量。
// 普通字符串
`In JavaScript '\n' is a line-feed.`
// 多行字符串
`In JavaScript this is
not legal.`
console.log(`string text line 1
string text line 2`);
// 字符串中嵌入变量
let name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`