在ES6中 允许使用箭头 (=>) 定义函数
声明一个箭头函数
let fn = (a,b)=>{
return a+b;
}
//调用函数
let result = fn(1,2);
console.log(result) //输出3
函数中的this指向的是window
function getName(){
console.log(this.name) //this == window
}
let getName2 = () =>{
console.log(this.name) //this == window
}
//设置window对象的name属性
window.name="aaa";
const school = {
name:"ATGUNGU"
}
//直接调用
getName() //aaa
getName2() //aaa
//call方法调用
getName.call(school) //ATGUNGU 此时this指向的是school
getName2.call(school) //aaa this指向还是window
在箭头函数中的this 是静态的,this始终指向函数声明所在作用域下的this的值
箭头函数不能作为构造实例化对象
let Person = (name,age) => {
this.name = name;
this.age = age;
}
let me = new Person("xiao",30);
console.log(me) //会报错
箭头函数不能不能使用arguments 变量
let fn = () => {
console.log(arguments) //会报错
}
fn(1,2,3)
箭头函数的缩写
1) 省略小括号,当形参有且只有一个的时候
let add = n => {
return n + n;
}
console.log(add(9)) //18
- 省略花括号,当代码体只有一条语句时,此时return 必须省略 而且语句的执行结果就是函数的返回值
let pow = n => n*n;
console.log(pow(5)) //25
箭头函数的应用
从数组中返回偶数的元素
const arr = [1,6,9,10,100,25];
普通函数的写法
const result = arr.filter(function(item){
if(item % 2 == 0){
return true
}else{
return false
}
})
console.log(result) //6 10 100
箭头函数的做法
const result = arr.filter(item => item % 2 === 0)
console.log(result) //6 10 100
总结
- 箭头函数中this 是静态的,this始终指向函数声明所在作用域下的this的值
- 箭头函数不能作为构造实例化对象,不能使用new操作符
- 不能使用arguments 变量
- 当形参有且只有一个的时候可以省略小括号
- 当代码体只有一条语句时,可以省略花括号,此时return 必须省略 而且语句的执行结果就是函数的返回值
- 箭头函数适合与this无关的回调,定时器,数组的方法回调,不适合与this有关的回调,事件回调,对象的方法