箭头函数Arrow Function

结构

const/let 函数名=(参数)=>函数体
注:
1)单个参数可省略圆括号;无参数或多个参数不可省略圆括号
2)单行函数体可同时省略{}、return;多行不可
3)返回单行对象,{}外加()避免与函数体的花括号混淆

无this

题目1:

const calc = {
    add: () => {
        console.log(this);
    };
};
calc.add();//window

解析:无this,故在add箭头函数作用域找不到;
对象无作用域; 往外就到了全局作用域
题目2:函数嵌套

const calc = {
    add: function () {
        const adder = () => {
            console.log(this);
        };
        adder();
    }
};
//隐式绑定
calc.add();//calc
//函数别名
const addFn = calc.add;
//隐式丢失
addFn(); 
//undefined(严格模式)-> window(非严格模式)

不能作为构造函数

常见于绑定事件
1)一般函数

document.onclick = function () {
    console.log(this);//document
}
document.addEventListener('click', function () {
    console.log(this);//document
}, true);

2)箭头函数

document.onclick = () => {
    console.log(this);
    //undefined(严格模式)-> window(非严格模式)
}
document.addEventListener('click', () => {
    console.log(this);
    //undefined(严格模式)-> window(非严格模式)
}, true);

无arguments

<button id=btn>开始</button>
<p id=result>0</p>
<script>
    const btn = document.getElementById('btn');
    const result = document.getElementById('result');
    // const timer = {
    //     time: 0,
    //     start: function () {
    //         // this指向timer
    //         var self = this;
    //         btn.addEventListener('click', function () {
    //             // this指向btn
                   //DOM绑定事件-绑定事件的DOM元素
    //             setInterval(function () {
    //                 // this无指向
    //                 self.time++;
    //                 result.innerHTML = self.time;
    //             }, 1000);
    //         }, false);
    //     }
    // };
    // timer.start();
	//利用箭头函数无this,向上一层寻找的特点
	//改写最里层的两个一般函数为箭头函数
    const timer = {
        time: 0,
        start: function () {
            // this指向timer
            btn.addEventListener('click', () => {
                // this指向btn
                setInterval(() => {
                    // 默认绑定:undefined(严格模式)
                    //window(非严格模式下)
                    this.time++;
                    result.innerHTML = this.time;
                }, 1000);
            }, false);
        }
    };
    timer.start();
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值