ES6——箭头函数

箭头函数:

1、单行代码可加也可不加{ },若需写多行则添加{ };单行代码不加{ }的话,箭头函数自带返回值;

//单行不加{ }的话,箭头函数自带返回值;
const add = (a, b) => a+b 

//多行则添加{ }
const add1 = (a, b) => {
	a += 1;
	return a + b;
};

console.log(add1(2, 2));

2、单行代码不需要返回值方法:

//行代码添加{ },以多行方式显示,则无返回值;
const pop = arr => {
    arr.pop();
}

//箭头指向添加void,即可;结果不返回或返回undefined;
const pop = arr => void arr.pop();

console.log(pop([1, 2, 3]));

3、箭头函数和function的区别:
1)箭头函数没有arguments类数组,要用扩展运算符代替,使用…args去拿参数(组成数组)

const log = (...args) => {
    console.log(args);
};

log(1, 2, 3);

2)箭头函数没有自己的this,箭头函数的this指向它被定义时自身所处环境的this,比如它在一个全局对象中的函数里被定义,那它的this就是window

const xiaoming = {
	name: '小明',
	say1: function() {
		console.log(this);
	},
	say2: () => {
		console.log(this);
	}
}

xiaoming.say1();//输出了小明对象
xiaoming.say2();//输出window

3)箭头函数中的this指向的就是自身所处环境getAge的this,而getAge中的this指向的就是xiaoming,省略了普通函数方法中需要进行保留this指向的操作;如果是普通函数的话,要在这个getAge方法里的第一行定义var that=this来保留this的指向。

//普通函数需要进行保留this指向的操作
const xiaoming = {
	name: 'xiaoming',
	age: null,
	getAge: function() {
		let _this = this; //保留this的指向
		// ...ajax
		setTimeout(function() {
			_this.age = 14;
			console.log(_this);
		}, 1000);

	}
}; 
//箭头函数中的this指向的就是自身所处环境getAge的this,而getAge中的this指向的就是xiaoming
const xiaoming = {
	name: 'xiaoming',
	age: null,
	getAge: function() {


		// ...ajax
		setTimeout(() => {
			this.age = 14;
			console.log(this);
		}, 1000);

	}
};

xiaoming.getAge();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值