es6-箭头函数以及函数参数

箭头函数

  • 写法

ES5:

   var show = function(){
       console.log('es5')
   }

ES6箭头函数:

  let show = ()=>{
      console.log('es5');
  }
  • 唯且仅有只有一个参数的时候()可以省略
  let show = a => {
      console.log(a);
  }
  • 当只有return一行的时候,可以省略return,{}
  let add = (a,b)=>a+b

this指向需要注意:es5,是谁调用this,this指向谁;es6中,不管谁调用this,this指向定义他的对象

rest

  • 对于参数不定的函数

ES5:

 function show(){
     console.log(arguments);
 }

arguments是伪数组,转化为数组,Array.from(arguments)或者Array.prototype.slice.apply(arguments),将他转化数组

ES6:

  function show(...arg){
      console.log(arg);//arg是一个数组
  }

es5中argument改变可以改变传入的参数的值,反之,亦然,而用了...arg的方法中,argument改变还是传入值改变,都不会影响互相

  • ...运算符还可以用来展开数组
   let arr = [1,2]
   let add = (a,b)=>a+b
   add(...arr); //3

...运算符不能直接用来做复制操作,否则会报错

函数值默认

   function show(a,b=1,c=2){
       console.log(a+b+c);
   }
   show(0); //3
   show(0,2) //4
   show(0,2,3) //5

猜你喜欢

转载自www.cnblogs.com/cmk-jumi/p/9156590.html
今日推荐