es6 箭头函数学习笔记

箭头函数是es6的一大亮点,大大简化了我们以前函数的编写方式,而且很直观,现记录下一些学习笔记。

1、不带参函数书写

let fun = () =>console.log('hello es6');
fun();	//hello es6
等同于es5的

var fun = function(){
	console.log('hello es6');
}
fun();	//hello es6
这里要注意的点是:① 如果执行语句不止一句的话,那么箭头右边应该用{ }来包含起来,然后用return来返回我们需要返回的值。如下:

let fun = () =>{
      let x=3, y = 5;
      return x+y;
}
fun() //8

如果直接返回的是一个对象的话那么应该用()包含起来,如下:

let fun = () =>({id:1,name:'es6666'});
fun();   //{id:1,name:'es6666'}

扫描二维码关注公众号,回复: 1915756 查看本文章


2、带参函数书写

如果是一个参数的话可以直接这样写:

let fun = x => x;
fun(8);    //8
等同于es5的

var fun = function(x){
    return x;
}
fun(8);    //8

多个参数的情况下可以这样写:

let fun = (x,y)=>x+y;
fun(3,5);    //8
等同于es5的

var fun = function(x,y){
   return x+y;
}
fun(3,5)   //8
你也可以给参数加个默认值,如下

let fun(x=3,y=5) =>x+y;
fun()   //8
fun(5,5)   //10
等同于es5的

var fun = function (x,y) {
  var x = x || 3;
  var y = y || 5;
  return x + y;
};
fun()   //8
fun(5,5)   //10


3、对象中的方法我们可以这样简写:

let obj = {
    name:'es6',
    age:2015,
    show(){
        console.log('hello '+obj.name);
    }
}
obj.show();   //hello es6
等同于es5的

var obj = {
    name:'es6',
    age:2015,
    show:function(){
        console.log('hello '+this.name);
   }
}
obj.show();   //hello es6

4、 es6函数的注意点

①、箭头函数不可以使用new来实例化对象,否则将会报错,如下:

let fun = () =>{
    let name = 'es6';
    console.log('hello '+name);
}
let funChild = new fun();   //报错,fun is not a constructor
FunChild();

②、 不可以使用argument对象,因为箭头函数体内根本没有这个对象,但可以使用rest参数(形式为"...变量名")代替,他会生成一个数组,用于获取函数多余的参数,如下:

let fun = (...params)=> console.log(params);    
  
fun(1,2,3,4)  //[1,2,3,4]  
  
let fun2 = (a,b,...params)=> console.log(params)  
  
fun2(1,2,3,4)  //[3,4]

③、函数体内的this指向的是定义时所在的对象,而不是使用时所在的对象,如下:

let obj = {
    name:"es6",
    show(){
        setTimeout(() => { // 使用箭头函数
            console.log(this);
        },1000)
    },
    fun:function(){
        setTimeout(function(){
            console.log(this);
        },1000)
    }
  }
  obj.show(); // 返回 obj 对象
  obj.fun(); // 返回window 对象

猜你喜欢

转载自blog.csdn.net/yemuxia_sinian/article/details/78270613