ES6及以后新增的常用API解析

35 阅读2分钟

1、let,const,var参考juejin.cn/post/705625…

2、箭头函数:箭头函数的this是定义时候决定的,普通函数this是使用时决定的

箭头函数特点:
    不能被用作构造函数(箭头函数的this是定义时决定的,this指向当前环境上下文)。
    没有原型链
    没有arguments
    
箭头函数的返回值:

ES6中的箭头函数和平时使用的函数的区别
-   **this**
   大部分人都知道是this不在动态绑定了,而是在写箭头函数的时候就定义好了
-   **返回值**
let fn1 = function (a, b) {
   a + b
}
let fn2 = function (a, b) {
   return a + b
}
let fn3 = (a, b) => a + b
let fn4 = (a, b) => { a + b }
let fn5 = (a, b) => {return a + b}

fn1(1, 2)    
fn2(1, 2)
fn3(1, 2)
fn4(1, 2)
fn5(1, 2)


结果 undefined/ 3/ 3/ undefined/ 3
实验证明,在不添加大括号的时候箭头函数会默认return语句,加了大括号就正常,

3、class

class Test{

    _name = '';
    constructor(name){
        this.name = name;
    }
    
    get name(){
        console.log('getter-'+`${this._name}`);
        return this._name;
    }
    
    set name(sb){
        this._name = sb;
        console.log('setter-'+`${this._name}`);
       
    }
}

const test = new Test();
test.name = 'sb';
test.name;

4、模版字符串

const a= ${a}--xx; const c = 我是换行 我是换行 我是换行 ;

// 编写render函数,实现template render 功能。
const year = '2021';
const month = '10';
const day = '01';

let template = '${year}-${month}-${day}';
let context = { year, month, day};//{year: year, month:month, day: day};

function render(template){
    return function(context){
        return template.replace(/\$\{(.*?)\}/g,(match,key)=>context[key] )
    }
}
console.log(render(template)(context));

5、解构

// 1、数组解构
    let [a, b, c] = [1,2,3];
    console.log(a,b,c);// 1,2,3
    // 对象数组解构
    let [a, b, c] = [{name: 1}, {name: 2}, {name: 3}];
    console.log(a,b,c) ; //{name: 1},{name: 2}, {name: 3}
    //...解构
    let [head, ...tail] = [1, 2,3,4]
    console.log(head, tail);//1, [2,3,4]
    // 嵌套解构
    let [a, [b], d] = [1, [2,3], 4];
    console.log(a, b, d); // 1,2,4
    // 解构不成功为undefined
    let [a, b, c] = [1]
    console.log(a, b, c) //1, undefined, undefined
    let [a=1, b=2] = [3];
    console.log(a, b); // 3, 2
// 2、对象解构

        let { f1, f2 } = { f1: 'test1', f2: 'test2' }
        console.log(f1, f2) // test1, test2

        // 可以不按照顺序,这是数组解构和对象解构的区别之一
        let { f2, f1 } = { f1: 'test1', f2: 'test2' }
        console.log(f1, f2) // test1, test2

        // 解构对象重命名
        let { f1: rename, f2 } = { f1: 'test1', f2: 'test2' }
        console.log(rename, f2) // test1, test2

        // 嵌套解构
        let { f1: {f11}} = { f1: { f11: 'test11', f12: 'test12' } }
        console.log(f11) // test11

        // 默认值
        let { f1 = 'test1', f2: rename = 'test2' } = { f1: 'current1', f2: 'current2'}
        console.log(f1, rename) // current1, current2
3、解构原理