ES6 箭头函数及箭头函数this指向

箭头函数

  1. 箭头左边是形参列表
    var fa = (a) => {};//只有一个参数的时候,形参外边的括号可以省略
    fa();
    
  2. 箭头右边是函数体
    //不写{}函数体的时候,默认直接返回内容
    var fa = () => 10;
    var fa = () => [1, 2, 3];
    var fa = () => 'hello';
    
    var a = 1,
    	b = 2;
    var fa = () => (a > b ? a : b);
    console.log(fa()); //2
    
    var fa = () => {
    	title: '周四';
    	// return 10;
    };
    console.log(fa()); //undefined
    
  3. 返回对象的时候js会把{}解析成函数体而不是对象,所以需要增加圆括号消除歧义
    报错
    var fa = () => {
    	title: '周四',
    	age: 22,
    };
    
    var fa = () => ({
    	title: '周四',
    	age: 22,
    });
    console.log(fa()); //{title: "周四", age: 22}
    

this指向

1.常规使用call改变当前调用者
	var f = function() {
		console.log(this);//{title: "周四"}
	};
	let obj = {
		title: '周四',
	};
	f.call(obj);
2. 匿名函数中的this指向
	let obj1 = {
	title: '周四',
	film: function() {
			console.log(this); //{title: "周四", film: ƒ}
			var _this = this;
			return function() {
				console.log(_this.title); //周四
				console.log(this); //window
			};
		},
	};
	obj1.film()();
3. 箭头函数中的this指向
	let obj = {
		title: '周四',
		film: () => {
			console.log(this); //window
			return function() {
				console.log(this); //window
			};
		},
	};

this指向几种情景

箭头函数不绑定当前调用者只与上下文环境有关

//情景一
var f = () => {
	console.log(this);//window
	return () => {
		console.log(this);//window
	};
};
f.call('宝宝')();

//情景二
var f = () => {
	console.log(this);//window
	return function() {
		console.log(this);//宝宝
	};
};
let a = f.call('baobao');
a.call('宝宝');

//情景三
var f = function() {
	console.log(this);//baobao
	return () => {
		console.log(this);//baobao
	};
};
let a = f.call('baobao');
a.call('宝宝');

//情景四
var f = function() {
	console.log(this); //baobao
	return function() {
		console.log(this); //宝宝
	};
};
let a = f.call('baobao');
a.call('宝宝');

注意

1、箭头函数是匿名函数,不绑定自己的this,arguments,super,new.target
2、箭头函数会捕获其所在上下文的this值,作为自己的this值,在使用call/apply绑定时,相当于只是传入了参数,对this没有影响;
3、箭头函数不绑定arguments,取而代之用rest参数…解决;
4、箭头函数当方法使用的时候,没有定义this绑定;
5、箭头函数不能作为构造函数,和 new 一起用就会抛出错误;
6、箭头函数没有原型属性;
7、不能简单返回对象字面量;

发布了54 篇原创文章 · 获赞 7 · 访问量 2068

猜你喜欢

转载自blog.csdn.net/baobao__/article/details/102492442