【笔记】ES6箭头函数的写法汇总

语法:

1、只有一个参数,可以不用写小括号:

var single = a => a;               //相当于var single = function(a){return a;}
console.log(single('hello, world'))// 'hello, world'
var single = a => console.log(a);  //相当于var single = function(a){console.log(a);}
single('hello, world')             // 'hello, world'

2、没有参数,要写一个空的小括号:

var noPare = () => console.log("No parameters"); 
noPare(); //"No parameters"

3、多个参数,参数在小括号中用逗号隔开:

var mulPare = (a,b) => console.log(a+b); 
mulPare(1,2); // 3

4、函数体有多条语句,用大括号包起来:

var differ = (a,b) => {
    if (a > b) {
        return a - b
    } else {
        return b - a
    }
};
differ(5,3);  // 2

5、返回对象时需要用小括号包起来,因为大括号被占用解释为代码块了:

var getObject = object => {
    // ...
    return ({
        name: 'Jack',
        age: 33
    })
}

6、直接作为事件,单条语句也要用大括号包起来:

form.addEventListener('input', val => {
    console.log(val);
});

7、作为数组排序回调,单条语句也要用大括号包起来:

var arr = [1, 9 , 2, 4, 3, 8].sort((x, y) => {
    return x - y ;
})
console.log(arr); // 1 2 3 4 8 9

注意:

1、与普通function实例没有区别,通过 typeof 和 instanceof 都可以判断它是一个function

var fn = a => console.log(a);
console.log(typeof fn); // function
console.log(fn instanceof Function); // true

2、this固定,不需要再多写一句var _this = this;去绑定this指向

fruits = {
    data: ['apple', 'banner'],
    init: function() {
        document.onclick = ev => {
            alert(this.data) 
        }
    }
}
fruits.init(); // ['apple', 'banner']

3、箭头函数不能用new

var Person = (name, age) => {
    this.name = name
    this.age = age
}
var p = new Person('John', 33) // error
发布了22 篇原创文章 · 获赞 1 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_42618289/article/details/80959445
今日推荐