函数的简化写法

一、ES6可以直接在大括号里面直接写入变量和函数,作为对象的属性和方法

let ad = document.getElementById('event')
        let name = "tom"
        let change = function() {
            console.log(1)
        }
        const school = {
            name,
            change,
            improve() {
                // 在ES6中,:function可以省略
                console.log(2)
            }
        }
        console.log(school.name, school.change);

二、箭头函数

例如:

ad.addEventListener("click", function() {
console.log(this)
let _this = this
setTimeout(function() {
console.log(this)
console.log(_this)
 }, 2000)
 }, false)

在上面的这个this中,是调用的window里面的this,而不是这个当前的函数块里的this,在setTimeout函数里面的this为window里的,要先在外面将this给保存下来:

let _this = this,然后再获取

箭头函数不需要写函数名:可以简写函数;上面的函数可以改写成:
例如:

ad.addEventListener("click", function() {
                setTimeout(() => {
                    console.log(this)
                }, 2000);
            }, false)

不需要将this保存即可使用,所以综上:

箭头函数适合与this无关的回调,定时器和数组的有关操作
箭头函数不适合与this的有关回调,事件回调和有关方法,只是不适合,不是不可以

箭头函数(ES6的新特性)箭头函数有返回值
原生函数的this指向他的调用者,如果没有则指向window
箭头函数的this指向的是他的定义者,而不是使用时的对象
箭头函数的this先在其作用域中找,如果没有,再往上找,直到找到为止
箭头函数不能作为构造实例化对象
省略花括号时,return也要省略

例如:

const arr = [1, 25, 32, 65, 87, 9, 5, 6, 8, 96]
        const result = arr.filter(function(item) {
            if (item % 2 == 0) {
                return true;
            } else {
                return false;
            }
        });
        // console.log(result)
        // 使用箭头函数可以简写
        const result1 = arr.filter(item2 => //arr.filter()对数组进行一个筛选
            item2 % 2 == 0 //如果只有一条函数,其花括号和return都要省略
        );
        console.log(result);
        console.log(result1);

以上为函数在ES6中的新特性和使用方法,希望对你有所帮助

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值