关于ES6箭头函数用法
- 箭头函数的省略写法
- 关于箭头函数中的this
- 不能作为构造函数实例化对象
- 不能使用arguments对象
- 箭头函数的使用场景
1、箭头函数的省略写法
箭头函数(放置形参的地方)=>{函数体},箭头函数没有名字,
通常将箭头函数赋值给一个变量,变量名字就是函数名字,通过变量名字调用函数就可以了
// 箭头函数(放置形参的地方)=>{函数体},箭头函数没有名字,
// 通常将箭头函数赋值给一个变量,变量名字就是函数名字,
// 通过变量名字调用函数就可以了
const fn = () => {
console.log("我是箭头函数")
}
fn()
如果形参只有一个,可以省略小括号,如果函数体中只有一条语句,可以省略花括号,且return必须省略
let arr = [1, 2, 3, 4, 5, 6];
//es5之前
var result = arr.filter(function(item) {
if (item % 2 == 0) {return true}
else { return false}
})
//使用箭头函数
var result = arr.filter(item => item % 2 === 0)
console.log(result);
2、关于箭头函数中的this
箭头函数不绑定this关键字,箭头函数没有自己的this关键字如果在箭头函数中使用this,this关键字将指向箭头函数 定义位置中的this,指向的是函数定义位置的上下文(windows)this
function getName() {
console.log(this.name);
}
var getName2 = () => {
console.log(this.name);
}
window.name = 'davis'
const person = {
name: 'lebron'
}
getName.call(person); //输出lebron
getName2.call(person); //输出davis
3、不能作为构造函数实例化对象
var Student = (sname, sage) => {
this.sname = sname;
this.sage = sage
}
let me = new Student('小明', 19);
4、不能使用arguments对象
var fn1 = () => {
console.log(arguments);
}
fn1(1, 2, 3, 4, 5);
5、箭头函数的使用场景
5.1 适合场景
适合与this无关的回调,定时器,数组的方法回调
<h2 id="content">点我</h2>
<body>
<script>
var item = document.getElementById('content')
item.addEventListener('click', function() {
console.log(this); //输出<h2 id="content">点我</h2>
setTimeout(function() {
console.log(this); //输出window对象
this.style.backgroundColor = 'pink'
}, 2000)
//17行提示错误,原因在这this在这里指向window,
//如果要使用,必须保留this,即that=this
//使用箭头函数没有问题
// setTimeout(() => {
// this.style.backgroundColor = 'pink'
// console.log(this);
//输出<h2 id="content">点我</h2>
// }, 2000);
}, true)
</script>
</body>
5.1 不适合场景
不适合与this有关的回调,DOM元素的事件回调(如果使用的话就指向外层作用域this的值),对象的方法