- ES6开始定义函数可以用箭头的方式,不用像以前一样function
- 格式: let 函数名称 = (形参列表) => {函数体}
简化代码
- 注意点:
- 如果函数体中只有一句代码, 那么{}可以省略
- 如果函数形参列表中只有一个形参, 那么()可以省略
- 如果函数体中只有一句代码, 并且是返回值, 那么return可以省略
let say = (name) => {return name}
let say = (name) => return name
let say = name => return name
let say = name => name
修改this
- ES6之前, 谁调用了这个函数, this就是谁
- 箭头函数没有this这个概念,箭头函数中的this会继承上一层作用域链,相当于在上一层作用域链var self = this,在箭头函数中用了这个self
- 场景一: 修改定时器中的this指针的指向
function Person() {
this.age = 666;
var self = this;
setTimeout(function () {
console.log(this); // window
console.log(self);
}, 1000);
setTimeout(()=>{
console.log(this); // Person
}, 1000);
/*
1.由于Person构造函数也是一个函数, 所以也会开启一个作用域
2.由于箭头函数是在Person构造函数的作用域中定义的, 所以数据Person构造函数作用域
3.箭头函数也是一个函数, 所以也会开启一个作用域
4.在箭头函数中使用this时, 会从所在的作用域链的上一层继承this
应用场景:
1. 让setTimeout/setInterval中的this变为我们想要的this
*/
}
- 注意点:
- 箭头函数没有this,所以箭头函数的this指向不能被call,apply,bind修改
- 箭头函数不能使用arguments,取代arguments可以用扩展运算符
function Student() {
this.age = 666;
// this.say = function () {
// // 谁调用就是谁
// // 可以被call/apply/bind方法修改
// console.log(this); //student
// }
this.say = ()=>{
// 从上一级的作用域继承
// 不可以被call/apply/bind方法修改
// 因为箭头函数自己没有this
// 因为箭头函数中的this只看定义, 不看调用
console.log(this);//student
}
}
var stu = new Student();
stu.say();
// stu.say.call({name:"lnj"});
// 注意点:
// 箭头函数中不能使用arguments
// function test() {
// console.log(arguments);
// }
let test = () => {
console.log(arguments);//报错
};
test(1, 3, 5);
网友评论