胡说八道es6

提及es6你们都很熟悉,有些es6新特性chrome等高级浏览器已经实现,不用咱们去编译了。今天我简单说下es6的一些特性,为何写呢?一方面自娱自乐,一方面是由于我有段时间不用就会忘,我给本身回回炉。说的不对,你们给我留言拍砖哈。html

一、声明变量有变化,再也不傻傻分不清

声明变量有两种方法,let和const。 let用来声明变量,const用来声明常量。jquery

什么是变量?变化的量。好比你的名字,公司地址。es6

什么是常量?永远不会变的东西。好比你的生日,固然你伪造的话那就不算。ajax

平时咱们声明var的变量能够重复声明,但let声明的变量不能重复声明,可是它们均可以重复赋值。chrome

const声明的常量即不能重复赋值也不能重复声明。json

二、做用域定义有变化,让你随手画个圈

以前js的做用域是用function来定义的,一个function内是一个做用域。如今是经过{}来定义的, 一个花括号内是一个做用域。数组

//var声明的i
var arr=[];
for (var i=0; i<10; i++){
    arr[i]=function(){
        console.log(i);
    }
}
arr[6]();//var声明的i指向i的地址,因此是10

//var声明的i若是要获得6,须要用一个当即执行和闭包。把i给num,

//而后在function里面console.log(num)便可,每个num都是一个新变量。
	var arr=[];
	for (var i=0; i<10; i++){
	    arr[i]=(function(num){
	         return function () {
            console.log(num);
        }
	    })(i);
	}
arr[6]();

//let声明的i
var arr=[];
for (let i=0; i<10; i++){
//let声明的i在这个花括号内是一直存在的,到下次循环的时候i=i+1
    arr[i]=function(){
        console.log(i);
    }
}
arr[6]();//6

复制代码

三、解构赋值二合一,省时省力好简洁

用人话来讲就是左边和右边结构同样。promise

第一能够省一部分赋值代码,让代码看起来简洁。浏览器

let [a,b]=[1,2];
console.log(a); //1
console.log(b); //2

复制代码

第二json简洁,提取方便。若是key和value是一样的命名,能够缩写。bash

let jsonData = {
  id: 42,
  status: "OK",
  data: [867, 5309]
};

let { id, status, data: number } = jsonData;

复制代码

四、有了字符串模板,远离+++拼接

let str="真好啊";
console.log("今每天气"+str+",心情也好!");
//如今能够写成
console.log(`今每天气${str},心情也好! `);

复制代码

五、函数增长新特性,箭头函数省省省,rest参数略略略

函数里面加了一个箭头函数和rest参数

箭头函数能够极大的缩写咱们的函数

若是参数只有一个,能够省略function(); 若是有return 返回,能够省略{return };

//一个参数和返回

//之前
let show=function(r){
    return r;
}

//如今
let show=r=>r;

//两个参数和返回
let show=(a,b)=>{return a+b};
复制代码

写起来是否是看着更简洁了,固然若是你不常写的话,以个人经验就是你不出一周就忘了怎么写了。

rest参数(...rest)顾名思义就是拿剩下的参数呗

function show(a,b,...arg){
    console.log(arg);
}
show(1,2,3,4,5);//[3,4,5]

复制代码

并且rest参数还能够帮咱们展开数组

let arr=[1,2,3];
console.log(...arr);
复制代码

展开有什么用呢?

var arr1 = ['a', 'b'];
var arr2 = ['c'];
var arr3 = ['d', 'e'];
// ES5 的合并数组
arr1.concat(arr2, arr3);
// [ 'a', 'b', 'c', 'd', 'e' ]
// ES6 的合并数组
[...arr1, ...arr2, ...arr3]
// [ 'a', 'b', 'c', 'd', 'e' ]
复制代码

能够看到展开后能够作合并和赋值。

六、数组有了新方法,遍筛累加很省劲儿。

map和forEach均可以遍历数组,既然均可以遍历数组,为何要定义两个方法呢?

其余这两个方法是有不一样的地方的:

内部代码在return的时候,forEach不会生成新数组。map会生成一个新数组。

foreEach要想改变数组须要在callback函数中去改。

//map改变数组
let arr=[1,3,5];
let curArr=arr.map(function(item,index){
    return item*2;
});
console.log(curArr);//[2,6,10]

//forEach改变数组
let arr=[1,3,5];
let curArr=arr.forEach(function(item,index){
    return arr[index]=item*2;
})
console.log(arr);//[2,6,10]
console.log(curArr);//undefined;
复制代码

filter是过滤器的意思,能够根据条件用来筛选数组中的元素。就比如流水线上的检查员,筛选出合格的产品。

let arr=[1,2,6];
let curArr=arr.filter(function(item,index){
    return item%2;
})
console.log(curArr);
复制代码

reduce是减小的意思,它能够执行数组的累积运算而后返回一个数。就比如搭积木,多个积木最后搭成一个东西。

let arr=[1,2,6];
let sum=arr.reduce(function(prev,cur,index,arr){
//prev是前一步的操做和
//cur是当前值
//index是当前的索引
//arr是当前的数组
    return prev+cur;
})
console.log(sum);
复制代码

七、对象继承新形式,声明继承更简单。

咱们先看下以前的对象声明和继承是怎么作的。

//定义父类
function Animal(name,color){
    this.name=name;
    this.color=color;
}
Animal.prototype.showName=function(){
    console.log(this.name);
}
Animal.prototype.showColor=function(){
    console.log(this.color);
}
let obj1=new Animal('mimi','白色');
obj1.showName();//mimi
obj1.showColor();//白色 
//定义子类
function Cat(name,color,age){
    Animal.apply(this,arguments);
    this.age=age;
}
//继承
Cat.prototype=new Animal();
Cat.prototype.constructor=Cat;
Cat.prototype.showAge=function(){
    console.log(this.age);
}
let obj2=new Cat('hh','红色',3);
obj2.showName();
obj2.showColor();
obj2.showAge();
复制代码

以前的继承作法是经过原型链先指向父类的原型,而后把子类的构造函数指向定义的构造函数。

这样原型链上就有了父类的方法,构造函数里面也会有父类的构造函数。

这样定义有个问题就是类和构造函数是一块儿的,单把构造函数拿出来,也能作类也能作函数。

es6里面更严谨了,声明类有了专门的class,继承有了extends

//父类声明
class Animal{
   //构造函数声明
    constructor(name,color){
        this.name=name;
        this.color=color;
    }
    //对象的方法声明
    showName(){
        console.log(this.name);
    };
    showColor(){
        console.log(this.color);
    }
}
let obj1=new Animal('mimi','白色');
obj1.showName();//mimi
obj1.showColor();//白色

//子类使用extends继承
class Cat extends Animal{
   
    constructor(name,color,age){
        //构造函数内继承父类的构造函数
        super(name,color);//super在这里表明了父类的构造函数
        this.age=age;
    }
    showAge(){
        console.log(this.age);
    }
}
let obj2=new Cat('haha','红色',6);
obj2.showAge();//6
obj2.showName();//haha
obj2.showColor();//红色
复制代码

八、异步回调好麻烦,aysnc和await来帮忙

咱们常见的异步回调会操做地狱回调,让你傻傻分不清,常常问本身,我代码在哪里呢?我逻辑走到哪里去了?

$.ajax({url:'/data.txt'},function(){//第一步
   $.ajax({url:'/data2.txt'},function(){//第二步
     $.ajax({url:'/data3.txt'},function(){//第三步
        $.ajax({url:'/data4.txt'},function(){//第四步
          $.ajax({url:'/data5.txt'},function(){//第五步
    
           })
        })
     })
   }) 
})
复制代码

若是咱们用async和await就能够实现同步写法实现异步回调的做用。

(async ()=>{
      let res=await $.ajax({
          url: '/data.txt'
       });
       //第一步
       console.log(res);
        let res2=await $.ajax({
          url: '/data2.txt'
       });
       //第二步
      console.log(res2);
      let res3=await $.ajax({
          url: '/data3.txt'
       });
       //第三步
      console.log(res3);
      let res4=await $.ajax({
          url: '/data4.txt'
       });
       //第四步
      console.log(res4);
      let res5=await $.ajax({
          url: '/data5.txt'
       });
       //第五步
      console.log(res5);
 })()
show();

复制代码

固然如今有不少提到Promise,Promise链式调用,咱们来看下若是用Promise要怎么用

let p1=new Promise(function(resolve,reject){
       $.ajax({
            url: 'data.txt',       
        })
        .done(function(data) {
           resolve(data);
        })
        .fail(function(err) {
           reject(err);
        }) 
   }) 
   p1.then(function(data){
   //成功
    console.log(data);
    return $.ajax({url: 'data2.txt'})//抛出Promise
   },function(err){
   //失败
    console.log(err);
   })
   //第二个Promise的处理
   .then(function(data){
       console.log(data);
   },function(err){
       console.log(err);
   })
复制代码

这里由于用的是jquery3.0的ajax,返回的实际上是一个promise,你能够打出来ajax的看下。

九、模块导入新方法,import和export要配合

es6用export来暴露模块的属性和方法,用import来引入模块。

a.js

let a=2;
let b=3;
export {a,b}
复制代码

index.html

<script type="module">
 import {a,b} from './a.js';
 console.log(a);
 console.log(b);
 </script>
复制代码

在页面中引入模块,type是必定要声明的,目前在谷歌最新版本的浏览器中测试的时候,若是不声明会报错。

es6的这些新特性是否是很神奇,好了,今天咱们先说到这里,工做中你们可使用,具体的原理,咱们后面讲。

相关文章
相关标签/搜索