原来ES6、ES7、ES8特性这么容易上手

203 阅读1分钟

欢迎大家关注我的博客还在开发中目前只有pc版本 林志伟博客;

class 类

class People {
    // 构造函数,实例化的时候将会被调用,如果不指定,那么会有一个不带参数的默认构造函数.
    constructor(name,job) {
      this.name = name;
      this.job = job;
    }
    // say是原型对象上的属性
    say() {
      console.log(`My name: ${this.name}, My job: ${this.job}`);
    }
  }
 
 let people = new People('Vinc','programmer');//实例化People
 people.say();
 
 console.log(people.hasOwnProperty('name')); //true
 console.log(people.hasOwnProperty('say')); // false
 console.log(people.__proto__.hasOwnProperty('say')); // true
 
 class Woman extends People{
  constructor(action) {
    // 子类必须要在constructor中指定super 函数,否则在新建实例的时候会报错
    // 如果没有置顶consructor,默认带super函数的constructor将会被添加
    super('Lily','student');
    this.action = action;
  }
  say() {
    console.log(super.say());
  }
 }
 
 let woman = new Woman('eat')
 woman.say();

箭头函数 Arrow

//常规使用
setTimeout(function(){
	console.log('500ms');
},500)
//箭头函数的例子
setTimeout(()=>{
	console.log('500ms');
},500)

模块化 Module

//test.js 单变量
export let name = 'Vinc';

//引用
import {name} from ./test.js;

//test.js 多变量
let name = 'Vinc';
let job = 'programmer';
export {name, job};

//test.js 导出函数
export function test() {return e};

字符串模板 ``

//常规字符串拼接方式,弊端当内容过多的时候拼接起来 '' + '' + '' + '' ...... 很难看很不好处理数据
let name = 'My name is' + name  + '.';
用了字符串模板一切就变得easy起来;
let name = `My name is ${name}.`

函数设置默认值

function test(width= 100,height= 100) {
	//do something
}

or

function test(width, height) {
	//do something
	let width = width || 100;
	let height = height || 100;
}

延展操作符

常规数组拼接 arr.push() or arr.concat(newArr)

新法语更加便捷
let arr = [...arrr, 'vinc'] or [...arr, ...newArr];
当然现在也支持对象克隆或属性拷贝

let obj = {...data} or {...data, name: 'vinc'};//后面的数值如果跟前面的相同则会覆盖前面

es7 includes 查找数组中是否包含

常规使用检验数据是否含有在数组里面
if(['vinc','jack'].indexOf('jack') == 1) {
	console.log('jack存在')
}

使用新语法

if(arr.includes('jack')) {
	console.log('jack存在')
}

es8 async/await

//常规使用
 get() {
	let res = new Promise((resolve, reject)=>{
		try{
			resolve('success')
		} catch(e) {
			reject(e)
		}	
	})
}

//新语法
async get() {
	let res = await $axios.get('/test');
	console.log(res);
}