es6语法
(1)模块化
通过import 来调用其他js文件中export的的模块
exp1.js
export default{
a:200
}
exp2.js
export function fn1(){
console.log('fn1')
}
export function fn2(){
console.log('fn2')
}
imp.js
//导入
import exp1 from 'exp1.js'
import {fn1,fn2} from 'exp2.js'
//调用
console.log(exp1)
fn1()
fn2()
(2)es6环境
用babel编译es6语法
简单配置.babelrc
{
"presets" : ["es2015", "latest"],
"plugins" : []
}
模块化工具可用webpack或rollup
(3)class语法
class MathHandle {
constructor( x, y){
this.x = x
this.y = y
}
add(){
return this.x + this..y
}
}
//创建class实例并调用add方法
var m = new MathHandle(1,2)
m.add()
继承语法:在构造函数中添加super()方法并传递应有的参数
(4)promise结合async/await处理异步请求
function loadimg(src) {
var promise = new Promise(function (resolve,reject) {
var img = document.createElement('img')
img.onload = function () {
resolve(img)
}
img.onerror = function () {
reject()
}
img.src = src
})
return promise
}
var src1 = 'https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png'
var src2 = 'https://img3.doubanio.com/view/photo/s_ratio_poster/public/p2382130301.webp'
var load = async function () {
var result1 = await loadimg(src1)
console.log(result1)
var result2 = await loadimg(src2)
console.log(result2)
}
load()
(5)es6其他常用功能
let/const:
let变量仅用于声明的块级作用域中
const变量为常量无法修改
反引号:
用反引号可以编辑多行字符串
const html =`<div>
<p>part1</p>
<p>part2</p>
</div>`;
解构赋值:
const obj = { a : 1 , b : 2 }
const { a, b} = obj
const arr = [ 'hello' , 'this' , 'world' ]
const [ a, b, c] = arr
函数参数默认赋值:
//当b没有参数传入时,默认赋值为0
function fn(a,b = 0){...}
箭头函数:
const arr = [1 ,2 ,3]
//普通函数
arr.map(function(item){
return item + 1
})
//箭头函数
arr.map(item => item + 1)