美文网首页
es6常用功能

es6常用功能

作者: 风雪之隅_b6f7 | 来源:发表于2019-04-12 10:26 被阅读0次

 1.let/const

            var i=10;       i=100;        console.log(i)//100;

            let b=3;        b=20;         console.log(b)//20

           const a=1;    a=100;       console.log(a)//报错

2.多行字符串/模版语法

//js写法:

var name='zhangsan',age=29,htnl='';

html +='<div>' ;

html +='  <p>'+name+'</p>';

html +='  <p>'+age+'</p>';

html +='  </div>';

//es6写法

const name='zhangsan', age=20;

const html=`

            <div>

              <p>${name}</p>

              <p>${age}</p>

            </div>

          `

3.解构赋值 

//js

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

var a=obj.a;

var b=obj.b;

var arr=['xxx','xy','yyy'];

var x=arr[0];

var xy=arr[1];

var y=arr[2];

//es6

const obj={a:100,b:200};

const{a,b}=obj;

const arr=['xxx','xy','yyy'];

const [x,y,z]=arr;

4.块级作用域 

    - for(let item in obj)

    - for 里面定义的item外面是无法访问 但是js  for(var item in obj)外能访问搭配item

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

 for(var item in obj){

    console.log(item)//a b

}

 //for循环以外也能访问的

  console.log(item)//b

   const obj={a:100,b:200};

   for(let item in obj){

         console.log(item)//a b

   }

  console.log(item)//报错  访问不到内部item块级作用域变了

5.箭头函数 

//js

var arr=[1,2,3];

arr.map(function(item){

    console.log(item+1)//2,3,4

})

arr.map(function(item,index){

    console.log('第'+index+'项的值:',item+1)//2,3,4

})

//es6

const arr=[1,2,3];

arr.map(item=>console.log(item+1));

arr.map((item,index)=>{console.log('第'+index+'项的值:',item+1)})

6.继承下的this指向问题

//js

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})

//es6

function fn(){

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

  var arr=[1,2,3];

  arr.map((item)=>{

    console.log(this) //{a:100}

  })

}

fn.call({a:100})

拓展call和apply继承

原理:调用一个对象的一个方法,用另一个对象替换当前对象

function add(a,b){

    return a+b; 

  }

  function sub(a,b){

    return a-b; 

  }

  //sub方法上去继承并调用add方法

  var a1 = add.apply(sub,[4,2]);

   console.log(a1) //6

  //add方法上去继承并调用sub方法

  var a2 = sub.apply(add,[4,2]);

  console.log(a2) //2

  /*call的用法*/

  var a1 = add.call(sub,4,2);

  console.log(a1)//6

//多重继承

function Class10(){

    this.showSub = function(a,b){

        console.log(a - b);

      } 

  }

  function Class11(){

    this.showAdd = function(a,b){

          console.log(a + b);

      } 

  }

  function Class12(){

    Class10.apply(this);

    Class11.apply(this); 

    // Class10.call(this);

    //Class11.call(this); 

  }

  var c2 = new Class12();

  console.log(c2.showSub(3,1));    //2

  console.log(c2.showAdd(3,1));    //4

相关文章

网友评论

      本文标题:es6常用功能

      本文链接:https://www.haomeiwen.com/subject/lbyqwqtx.html