sunny-cheng  

箭头函数

使用=>来定义  function(){}等于()=>{}

ES5函数
 let add = function (a, b) {
    return a + b;
 }
    console.log(add(3,5));  //8

箭头函数
let add2 = (a, b) => {
   return a + b;
 }
   console.log(add2(3,5));    //8

注意点
  当箭头函数要返回对象的时候,为了区分于代码块,要用 () 将对象包裹起来
var f = (id,name) => ({
  id: id, name: name
});
f(6,2); // {id: 6, name: 2}

// 箭头函数里面没有 this 对象,
// 此时的 this 是外层的 this 对象,即 Window 

var func = () => {
  console.log(this)
}
func(55);  // Window


没有this、super、arguments 和 new.target 绑定。
箭头函数体中的 this 对象,是定义函数时的对象,而不是使用函数时的对象。
var Person1 = {
  'age': 18,
  'sayHello': function () {
    setTimeout(()=>{
    console.log(this.age);
    });
  }
};
var age = 20;
Person1.sayHello(); // 18

 

默认参数
 function add(a, b = 20) {
        return a + b;
    }
        console.log(add(30));   //50

    b = 20 使用函数默认参数只有在未传递参数,或者参数为 undefined 时,才会使用默认参数,null 值被认为是有效的值传递。

不定参数

...参数,当参数个数不确定时候用不定参数
function f(...values){ console.log(values.length); } f(
1,2); //2 f(1,2,3,4); //4

 

posted on 2020-05-28 21:33  sunny-cheng  阅读(108)  评论(0编辑  收藏  举报