箭头函数
箭头函数的语法:let 变量名 = ()=>{}
箭头左边的(),是否能省略掉?
1.不带参数,()不能省略,起到站位符的作用
let bar = () => {
console.log('bar')
}
bar();
2.带一个参数,()可以省略( 建议使用)
let bar1 = a => {
console.log('bar1')
}
bar(5);
3.带多个参数,()不能省略,起到一个整体
let bar2 = (a,b) => {
console.log('bar2')
}
bar(5,9);
箭头右边的{},是否能省略?
主体是一个表达式的时候,{}省略的话,那主体的结果会自动返回,如果加上{},需要手动retrue
let bar3 = (a, b) => a + b;
console.log(bar3(5, 8))
箭头函数this的指向
1.普通函数在定义额时候this不知道指向谁,在使用的时候才会知道this指向谁
2.箭头函数在定义的时候就已经确定下来this指向谁了
(1)全局中指向window
(2.)箭头函数的指向只要看外层是否有函数,如果有的话跟外层函数的this保持一致,否则指向全局
<body>
<button type="button" id='btn1'>按钮1</button>
<button type="button" id='btn2'>按钮2</button>
<script type="text/javascript">
let btn1 = document.getElementById('btn1')
let btn2 = document.getElementById('btn2')
btn1.onclick = ()=>{
console.log(this) //window
}
let obj = {
name:'我们',
say:()=>{
btn2.onclick =()=>{
console.log(this) //window
}
}
}
obj.say()
</script>
</body>