6.箭头函数

箭头函数

ES6允许使用【箭头】(=>)定义函数

声明一个函数

let fn = function(){

}
let fu = (a,b)=>{
	return a+b;
}
//调用函数
let result = fu(1,2);
console.log(result);

this是静态的,this始终指向函数声明时所在作用于下的this的值
function getName(){
	console.log(this.name);
}
let getName2 = () => {
	console.log(this.name);
}

//1.设置window对象的name属性

window.name = 'study';
const school ={
	name:"bad"
}

//直接调用
getName();
getName2();

//call 方法调用
getName.call(school);//bad
getName2.call(school);//study

//2.不能作为构造实例化对象
let Person = (name,age) =>{
	this.name = name;
	this.age = age;
}
let me = new Person('xiao',30);
console.log(me);//报错:Person is not a constructor

//3.不能使用arguments变量
let fu = () => {
    console.log(arguments);
}
fn(1,2,3);//报错:arguments is not defined

//4.箭头函数的简写
	//1)省略小括号,当形参有且只有一个的时候
	let add = n => {
        return n+n;
    }
    console.log(add(9));
	//2)省略花括号,当代码体只有一条语句的时候,此时return必须省略
	//而且语句的执行结果就是函数的返回值
	let pow = n => n*n;
	console.log(pow(8));

箭头函数的实践

//需求1 点击div 2s 后颜色变成粉色
//获取元素
let ad = document.getElementById('ad');
//绑定事件
ad.addEventListener('click',function(){
    //ES5做法,保存this的值
    let _this = this;
    //定时器
    setTimeout(function(){
        _this.style.background = 'pink;
    },2000);
     //ES6做法
    setTimeout(() => {
        this.style.background = 'pink;
    },2000);
})

//需求2 从数组中返回偶数元素
const arr = [1,6,9,10,100,25];
//ES5
const result = arr.filter(function(item){
    if(item % 2 ===0){
        return true;
    }else{
        return false;
    }
})
console.log(result);//[6,100]
//ES6
const result = arr.filter(item => item % 2 ===0);
console.log(result);//[6,100]

  • 箭头函数适合与this无关的回调。
    例如:定时器,数组的方法回调

  • 箭头函数不适合与this有关的回调。
    例如:事件回调,对象的方法

相关文章

原文连接:https://www.cnblogs.com/dupd/p/5951311.htmlES6...
以为Es6,javascript第一次支持了module。ES6的模块化分为导...
视频讲解关于异步处理,ES5的回调使我们陷入地狱,ES6的Prom...
TypeScript什么是TypeScript?TypeScript是由微软开发的一款开...
export class AppComponent { title = 'Tour of heroes...
用 async/await 来处理异步昨天看了一篇vue的教程,作者用as...