ES6其他常用功能
let 和const
模板字符串
传统写法
//传统写法var name = 'zhangsan' , age = 20, html = '';html += '';html += ''//"'+ name +'
'; html += ''+ age + '
'; html += '"zhangsan
20
ES6写法
const name = 'zhangsan', age =20;const html = ``; //${name}
${age}
//zhangsan
//20
//
解构赋值
传统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