2019-09-27 ES6标准入门 笔记

123 阅读7分钟

第1章 简介

第2章 let和const命令

  1. let
    1. 不存在变量提升
    2. 暂时性死区
    var tmp = 123;
    if(true){
        tmp = 'abc'; //ReferenceError
        let tmp;
    }
    
    1. 不允许重复声明
  2. do表达式:本质上,块级作用域是一个语句,将多个操作封装在一起,没有返回值
    let x = do{
        let t = f();
        t*t+1
    }
    
  3. const
    1. 本质:实际上保证的并不是变量的值不得改动,而是变量指向的那个内存地址不得改动。对于简单类型的数据,值就保存在变量指向的内存地址中。因此同等于常量。
      如果真的想要冻结对象,应该使用Object.freeze方法
    const foo = Object.freeze({});
    foo.prop = 123; //不会成功
    

第3章 变量的解构赋值

  1. 数组的解构赋值
    let [a,b,c]=[1,2,3]
    //a=1,b=2,c=3
    
    需要模式匹配,即等号两边的模式相同
    let [foo,[[bar],baz]] = [1,[[2],3]];
    //foo = 1
    //bar = 2
    //baz = 3
    
  2. 默认值
    let [foo = true] = []
    foo //true
    
  3. 对象的解构赋值
    let {foo,bar} = {foo:"aaa",bar:"bbb"};
    foo // "aaa"
    bar // "bbb"
    
    let {foo:bar} = {foo:"aaa",bar:"bbb"};
    baz //"aaa"
    foo // error:foo is not defined
    
  4. 字符串的解构
    let [a,b,c,d,e] = 'hello';
    a // "h"
    b // "e"
    c // "l"
    d // "l"
    e // "o"
    
  5. 不能使用圆括号的情况
    声明语句不能使用圆括号,赋值语句可以
    1. 变量声明语句
    let [(a)] = [1]; //报错
    
    1. 函数参数
    function f([(z)]){return z;} //报错
    
    1. 赋值语句的模式
    ({p : a}) = {p 42}; //报错
    
  6. 用途
    1. 交换变量的值
    let x = 1;
    let y = 2;
    [x,y] = [y,x]
    
    1. 从函数返回多个值
    function example(){
        return [1,2,3];
    }
    let [a,b,c] = example();
    
    function example(){
        return {
            foo:1,
            bar:2
        };
    }
    let {foo,bar} = example();
    
  7. 提取JSON数据
    let jsonData = {
        id:42,
        status:"OK",
        data:[867,5309]
    }
    let {id,status,data:number}
    console.log(id,status,number)
    // 42 ,"OK" ,[867,5309]
    
  8. 遍历Map解构 使用for...of遍历循环
    let map = new Map();
    map.set('first','hello');
    map.set('second',"world");
    
    for(let [key,value] of map){
        console.log(keyi + " is " + value);
    }
    //first is hello
    //second is world
    

第4章 字符串的扩展

  1. 字符串的遍历器接口
    for(let codePoint of 'foo'){
        console.log(codePoint)
    }
    //"f"
    //"o"
    //"o"
    
  2. 模板字符串 有空格的情况,如果不想要,可以使用trim()方法
    `<ul>
        <li>first</li>
        <li>second</li>
    </ul>`.trim()
    
    字符串模板可以调用方法
    function fn(){
        return "Hello World";
    }
    `foo ${fn()} bar`
    //foo Hello World bar
    

第5章 正则的扩展

第6章 数值的扩展

Number.isFinite()//是否是有限数,
Number.isNaN()//是否不是一个数值,
Number.isInteger()//是否是一个整数
  1. Number.parseInt(),Number.parseFloat()
    ES6 将全局方法parseInt()和parseFloat()全部移植到了Number对象上面,行为完全不变。
  2. Math 对象的h扩展
    Math.sign()//判断一个数是什么符号
    参数为正数,返回+1
    参数为负数,返回-1
    参数为0或者-1,返回0或者-0
    其他值,返回NaN
    

第7章 函数的扩展

  1. 默认值
    function log(x,y = 'World'){
        console.log(x,y);
    }
    log('Hello') //Hello World
    log('Hello','China') //Hello China
    log('Hello','') //Hello
    
    function Point(x = 0,y = 0){
        this.x = x;
        this.y = y;
    }
    let p = new Point();
    p //{x:0,y:0};
    
  2. 与解构赋值默认值结合使用
    function foo({x,y = 5}){
        console.log(x,y);
    }
    
    foo({}) //undefined,5
    foo({x:1}) //1,5
    foo({x:1,y:2}) //1,2
    foo() // TypeError:Canot read property 'x' of undefined
    
  3. rest参数
    function add(...values){
        let sum = 0;
        
        for (var val of values){
            sum += val;
        }
        
        return sum;
    }
    
    add(2,5,3)  //10
    
  4. 严格模式
    如果函数参数使用了默认值,解构赋值或者扩展运算符,那么函数内部就不能显示设定为严格模式,否则会报错。
  5. name属性
    function foo(){}
    foo.name //"foo"
    
    var f = function(){};
    //ES5
    f.name //""
    //ES6
    f.name //"f"
    
    var bar = function baz(){}
    bar.name //"baz"
    
  6. 箭头函数
    1. 基本用法
    var f = v => v;
    //同等与
    var f = function(v){
        return v;
    }
    
    如果不需要参数或者需要多个参数,就使用圆括号代表参数部分。
    var f = () => 5;
    //同等与
    var f = function () { return 5 };
    
    var sum = (num1, num2) => num1 + num2;
    //同等与
    var sum = function(num1,num2){
        return num1 + num2;
    };
    
    1. 绑定this
    foo::bar;
    //同等与
    bar.bind(foo)
    
    foo::bar(...argument);
    //同等与
    bar.apply(foo,arguments);
    
  7. 尾调用优化
    1. 尾调用
    function f(x){
        return g(x);
    }
    
    1. 尾递归
    function factorial(n){
        if(n===1) return 1;
        return n*factorial(n-1);
    }
    factorial(5) //120
    

第8章 数组的扩展

  1. 扩展运算符
console.log(...[1,2,3])
// 1 2 3

console.log(1,...[1,2,3],5)
// 1 2 3 4 5
  1. 扩展运算符的应用
[1,2].concat(more)
//ES6
[1,2,...more]

const [first,...rest]=[1,2,3,4,5];
first //1
rest //[2,3,4,5,]

[..."HELLO"]
//["H","E","L","L","O"]

  1. Array.of()
Array.of()方法用于将一组值转换为数组
Array.of(3,11,8) // [3,11,8]
  1. find()和findIndex()
返回值
[1,4,-5,10].find((n) => n < 0)
// -5

返回位置
[1,5,10,15].findIndex((value,index,arr)=>value>9)
// 2
  1. fill()
['a','b','c'].fill(7)
//[7,7,7]

['a','b','c'].fill(7,1,2) //从1号位置开始,到2号位置结束
//['a',7,'c']
  1. entries(),keys(),values()
for(let index of ['a','b'].keys()){
    console.log(index)
}
//0
//1

for(let index of ['a','b'].values()){
    console.log(index)
}
//'a'
//'b'

for(let [index,elem] of ['a','b'].entries()){
    console.log(index,elem)
}
//0 'a'
//1 'b'
  1. includes()
[1,2,3].includes(2) //true
[1,2,3].includes(4) //false
[1,2,NaN].includes(NaN) //true

[1,2,3].includes(3,3); //false 第二个参数是起始位置

第9章 对象的扩展

  1. 属性的简洁表示法
var foo = 'bar';
var baz = {foo};
baz // {foo:"bar"}

//等同于
var baz = {foo:foo};

function f(x,y){
    return {x,y};
}
//等同于
function f(x,y){
    return {x:x,y:y};
}

f(1,2) //object {x:1,y:2}
  1. object,assign()
var target = { a:1 };
var source1 = { b:2 };
var source2 = { c:3 };
object.assign(target,source1,source2);
target //{a:1,b:2,c:3}
  1. 对象属性的遍历
一共有5种方法可以遍历
1. for...in
2. Object.keys(obj)
3. Object.getOwnPropertyNames(obj)
4. Object.getOwnPropertySymbols(obj)
5. Reflect.ownKeys(obj)

第10章 Symbol

Symbol("foo") === Symbol("foo") //false

var s1 = Symbol.for('foo');
var s2 = Symbol.for('foo');

s1 === s2 //true

var s1 = Symbol.for("foo");
Symbol.keyFor(s1) //"foo"

第11章 Set和Map数据解构

  1. Set基本用法
    set类似数组,成员是唯一的,没有重复
    
  2. Set实例的属性和方法
add(value):添加某个值,返回Set解构本身
delete(value):删除某个值,返回一个布尔值,表示删除是否成功
has(value):返回一个布尔值,表示是否为Set的成员
clear():清除所有成员,没有返回值

Array.from方法可以将Set解构转为数组
  1. Map基本用法
const m = new Map();
const o = {p:'Hello World'};

m.set(o, 'content')
m.get(o) // "content";

m.has(o) //true
m.delete(o) //true
m.has(o) //false
  1. 实例的属性和操作方法
size: 返回Map结构的成员总数
set(key,value): 设置key所对应的键值
get(key):读取key对应的键值
has(key):判断某个键是否在Map数据结构种
delete(key):删除某个键,成功/true,失败/false
clear(key):清除所有成员

第12章 Proxy

第13章 Reflect

第14章 Promise对象

1.基本用法:
var promise = new Promise(function(resolve,reject){
    // ...some code
    if(/* 异步操作成功 */){
        resolve(value)
    }else{
        reject(error)
    }
});

resolve的作用:将Promise对象的状态从"未完成"变为"成功" 即从Pending变为Resolved
reject的作用:将Promise对象的状态从"未完成"变为"失败" 即从Pending变为Rejected

promise.then(function(value){
    // success
},function(error){
    // failure
});

2.Promise.resolve()
将现有对象转为Promise()对象,状态为resolve
Promise.resolve('foo')
//同等与
new Promise(resolve => resolve('foo'))

3.Promise.reject()
将现有对象转为Promise()对象,状态为reject
Promise.reject('error')
//同等与
new Promise(reject => reject('error'))

第15章 lterator和for...of循环

1.lterator 遍历器

2.for...of 循环
数组:
const arr = ['red','green','blue']

for(let v of arr){
    console.log(v); //red green blue
}

第16章 Generator函数的语法

yield 只能用在Generator函数里

function* genFun(){
    yield 1;
    yield 2;
    return 'ending';
}
genFun.next() //{value:1,done:false}
genFun.next() //{value:2,done:false}
genFun.next() //{value:'ending',done:true}

第17章 Generator函数的异步应用

第18章 async函数

1.基本用法
function timeout(ms){
    return new Promise((resolve) => {
        setTimeout(resolve,ms);
    })
}
async function asyncPrint(value,ms){
    await timeout(ms);
    console.log(value)
}
2.使用形式
//函数声明
async function foo(){}

//函数表达式
const foo = async unction(){}

//对象方法
let obj = { async foo(){}};
obj.foo().then(...)

//箭头函数
const foo = async() => {}

3.语法
async function f(){
    return 'hello world';
}
f().then(v => console.log(v))
//'hello world'

第19章 Class的基本语法

class Point{
    constructor(x,y){
        this.x = x;
        this.y = y;
    }
    
    toString(){
        return '(' + this.x + ',' + this.y + ')';
    }
}
方法之间不需要逗号分隔,加了会报错
类的方法都是定义在prototype对象上

class Bar{
    doStuff(){
        console.log('stuff');
    }
}
var b = new Bar()
;
b.doStuff() //"stuff"

第20章 Class的继承

Class可以通过extends关键字实现继承

class ColorPoint extends Point{
    
}

第21章 修饰器

第22章 Module的语法

export deault命令

第23章 Module的加载实现

第24章 编程风格

第25章 读懂ECMAScript规格

第26章 ArrayBuffer