004--面试之ES6其他常用的功能

ES6其他常用功能

let 和const


模板字符串

传统写法

//传统写法
var name = 'zhangsan' ,  age = 20, html = '';
html += '<div>';
html += '<p>'+ name +'</p>'; 
html += '<p>'+ age + '</p>'; 
html += '</div>'
//"<div><p>zhangsan</p><p>20</p></div>"

ES6写法

const name = 'zhangsan', age =20;
const html = `
    <div>
        <p>${name}</p>
        <p>${age}</p>
    </div>
`;
    // <div>
    //     <p>zhangsan</p>
    //     <p>20</p>
    // </div>

解构赋值

传统ES5写法

   var obj = {a: 100, b: 200}
    var a = obj.a
    var b = obj.b

    var arr = ['xxx','yyy','zzz']
    var x = arr[0]
    var z = arr[2]

ES6写法

 //ES6写法
    const obj = {a: 100, b: 200}
    const {a,b} = obj
    const arr = ['xxx','yyy','zzz']
    const [x,y,z] = arr

块级作用域

传统的写法

 //块级作用域
    var obj = {a: 100, b: 200}
    for(var item in obj){
        console.log(item);
    }
    console.log(item);//外部能访问到

ES6的写法

 //ES6写法
    const obj = {a: 100, b: 200}
    for(let item in obj){
        console.log(item);
    }
    console.log(item);//外部不能访问到

函数默认值

 //函数默认值
    function fn(a,b) {
        if (b == null) {
            b = 0
        }
    }
    //es6
    function fn(a,b=0) {
        
    }

箭头函数

var arr = [1, 2, 3];
arr.map(function (item) {
    return item + 1;
})

const arr = [1, 2, 3];
arr.map(item => item + 1);
arr.map((item, index) => {
    console.log(item);
    return item + 1;
});

箭头函数的this

普通函数的this一般为

function fn() {
    console.log('real', this)  // real {a: 100}

    var arr = [1, 2, 3]
    arr.map(function (item) {
        console.log(this)  // window
    })
}
fn.call({a: 100})

// Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}
// Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}
// Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}

箭头函数的this指向上述的 {a:100}


 

2019-05-09  16:53:28

工欲善其事,必先利其器
原文地址:https://www.cnblogs.com/ccbest/p/10839504.html