Es6-箭头函数

107 阅读1分钟

箭头函数:新潮的函数写法

适当的省略function和return关键字 缺点:破坏了代码的可读性

普通函数写法

function add(x){
    return x+10;
}

箭头函数写法

var add = x => x + 10;

无参数无返回值的箭头函数写法:

function(){
    alert("hello world")
}

//无参数无返回值的箭头函数写法
var show = () => {
    alert("hello world");
}

有一个参数无返回值的箭头函数写法:

function(num){
    alert(num);
}

//有一个参数无返回值的箭头函数写法:
var xxx = (num) =>{
    alert(num);
}

有一个参数一个返回值箭头函数写法:

function add(x){
    return x+10;
}

//有一个参数一个返回值箭头函数写法:
var add = x => x + 10;

有多个参数有返回值的箭头函数写法:

function shou (x,y){
    alert(x+y);
}

//有多个参数有返回值的箭头函数写法:
var shou = (x,y) => {
    alert(x+y);
}

箭头函数的注意事项:

  • 箭头函数不能用new
  • 箭头函数如果返回值是一个对象,一定要加() ,例如:
var show = () => ({

})
  • 箭头函数的this,指向的是上一层函数的主人,例如:
var person = {
    username:"钢铁侠";
    show:function(){
        alert(person.username);
        alert(this.username);
    }

    
    add: () => {
        alert(person.username);
        alert(this.username);
    }
}

person.shou(); //show里面的alert都指向 钢铁侠
person.add(); //add里面的一个指向钢铁侠,一个指向window(因为没有上一层了)