适用范围:
- 作为回调函数传入某一个函数中, 这样就能保持外部的this
梗概:
- ES6 新增了箭头函数。
- 定位上,箭头函数就是纯粹的一个保存在变量里面的“函数”(并且从定位上来说也不是一个“方法”)
语法:
(参数1, 参数2, …, 参数N) => { 函数声明 }
(参数1, 参数2, …, 参数N) => 一条表达式//不能带return
// 相当于:(参数1, 参数2, …, 参数N) =>{ return 表达式; }当只有一个参数时,圆括号是可选的:
(单一参数) => {函数声明}
单一参数 => {函数声明}没有参数的函数应该写成一对圆括号:
() => {函数声明}1. 说明:
- 当我们使用箭头函数的时候,箭头函数会默认帮我们绑定外层 this 的值,所以在箭头函数中 this 的值和外层的 this 是一样的。
- 箭头函数是不能通过arguments获取传入实参
- 没有prototype(原型对象)
- 不能作为构造函数
- 在class语法糖中声明一个箭头函数会被当作静态属性,而不是一个方法 ^ndrabj
- 即不会被添加到prototype(原型对象)中
实例:
之一
// ES5
var x = function(x, y) {
return x * y;
}
// ES6
const x = (x, y) => x * y;之一
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
say() {
console.log('名字' + this.name + '今年' + this.age);
}
run = () => {
console.log(this.name + '可以run');
}
eat() {
console.log('可以吃');
}
}
class CloneMan extends Person {
constructor(name, age) {
super(name, age);
}
say = () => {
console.log('我叫' + this.name + '今年' + this.age);
}
run() {
console.log(this.name + '真的可以run');
}
eat = () => {
console.log('还可以吃');
}
}
const tom = new CloneMan('tom', '20')
tom.say() //我叫tom , 今年20 CloneMan的say
tom.run() //tom可以run Person的run
tom.eat() //还可以吃 CloneMan的eat