箭头函数
一.ES6允许使用|箭头|(=>)定义函数
1.声明函数
let fn=function(){}
let fn1=(a,b)=>{
return a+b
}
//调用函数
console.log(fn1(1,2));
2.函数特性
1.this是静态的,this始终指向函数声明时所在的作用域下的this值
function getName() {
console.log(this.name);
}
let getName2 = () => {
console.log(this.name);
};
//设置window对象的name属性
window.name = ‘小红’;
const SCHOOL = {
name: ‘ATGUTGU’
};
//直接调用
getName(); //小红
getName2(); //小红
//call方法调用
getName.call(SCHOOL); //ATGUTGU
getName2.call(SCHOOL); //小红
call() 方法是预定义的 JavaScript 方法。
它可以用来调用所有者对象作为参数的方法。
2.不能作为构造实例化对象
let Person = (name, age) => {
// this.name = name;
// this.age = age;
// }
// let me = new Person(‘xiao’, 30)
// console.log(me); //error Person is not a constructor
3.不能使用agruments变量(arguments 是一个对应于传递给函数的参数的类数组对象。)
let fn = () => {
console.log(arguments);
}
fn(1, 2, 3); //error arguments is not defined
4.箭头函数简写
//(1)省略小括号:当形参有且只有一个时
let add = n => {
return n + n;
}
console.log(add(9)); //18
//(2)省略花括号,当代码有且只有一条语句时,而且return语句必须省略
//而且语句的执行结果就是函数的返回值
let pow = n => n * n;
console.log(pow(8)); //64
二.箭头函数实践
let ad = document.getElementById(‘ad’);
//绑定事件
ad.addEventListener(‘click’, function() {
//保存this
// let _this = this;
//定时器
setTimeout(() => {
//修改背景颜色 this
this.style.background = ‘pink’
}, 2000)
});
//箭头函数适合于与this无关的回调,定时器,数组方法回调
//需求2从数组中返回偶数的元素
const ARR = [1, 6, 9, 100, 25];
// const result = ARR.filter(function(item) {
// if (item % 2 === 0) {
// return true;
// } else {
// return false
// }
// });
// console.log(result);
// const result = ARR.filter(item => {
// if (item % 2 === 0) {
// return true;
// } else {
// return false;
// }
// })
const result = ARR.filter(item => item % 2 === 0)
console.log(result);
//箭头函数不适合与this有关的回调,事件回调,对象的方法
注:filter()方法
注意:filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
注意: filter() 不会对空数组进行检测。
注意: filter() 不会改变原始数组。