【ES6】JavaScript函数-箭头函数-this指向-简写

ES6 允许使用“箭头”(=>)定义函数

1. 定义箭头函数

原本函数的定义方式

var fn = function(a, b) {
    
    
	return a + b;
};

箭头函数的写法

let fn = (a, b) => {
    
    
	return a + b;
};

2. 箭头函数注意点

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

window.name = 'YK菌';
const person = {
    
    
	name: 'yk';
}

// 直接调用
getName() // YK菌
getName2() // YK菌

// call 方法调用
getName.call(person); // yk
getName2.call(person); // YK菌   (this指向没有改变)
  1. 不可以当作构造函数实例化对象,即不可以使用new命令,否则会抛出一个错误

  2. 不可以使用arguments对象,该对象在函数体内不存在。(如果要用,可以用 rest 参数代替)

  3. 不可以使用yield命令,因此箭头函数不能用作 Generator 函数。

3. 箭头函数简写

  1. 省略小括号,当形参有且只有一个
let add = n => {
    
    
	return n+n;
}
  1. 省略大括号(return 也要省略), 当代码体只有一条语句
let add = (n) => n+n;
  1. 最后放在一起省略就是
let add = n => n+n;

4. 箭头函数应用

  1. 案例一 点击div两秒后变色
let ad = document.getElementById('ad');
ad.addEventListener("click", function(){
    
    
	let _this = this; // 保存this的值
	setTimeout(fucntion(){
    
    
		_this.style.backgroud = 'pink';
	}, 2000);

用箭头函数不用保存之前的this

let ad = document.getElementById('ad');
ad.addEventListener("click", function(){
    
    
	setTimeout(() => {
    
    
		this.style.backgroud = 'pink'; //指向的就是ad
	}, 2000);
  1. 案例二 从数组中返回偶数元素
    原来做法
const arr = [1,2,3,4,5,6];
const result = arr.filter(function(item){
    
    
	if(item % 2 === 0){
    
    
		return ture;
	}else {
    
    
		return false;
	}
});

使用箭头函数

const arr = [1,2,3,4,5,6];
const result = arr.filter(item => item%2 ===0);
  • 箭头函数适合与this无关的回调函数;如定时器,数组方法回调
  • 箭头函数不适合与this有关的回调函数;如事件回调,对象的方法

参考资料

  1. 尚硅谷ES6教程 https://www.bilibili.com/video/BV1uK411H7on?p=9
  2. 阮一峰ES6教程 https://es6.ruanyifeng.com/#docs/function
  3. JavaScript高级程序设计(第四版)P288.291 https://www.ituring.com.cn/book/2472

猜你喜欢

转载自blog.csdn.net/weixin_44972008/article/details/112929712