通过vue.js 学习来总结es6语法中的箭头函数,箭头函数原理分析。

21 篇文章 1 订阅

首先我们来学习一下大神对箭头函数的剖析:

----------------------------------------------横线部分来自廖雪峰大神的官方网站------------------------------------------------------------------------------

ES6标准新增了一种新的函数:Arrow Function(箭头函数)。

为什么叫Arrow Function?因为它的定义用的就是一个箭头:

x => x * x

上面的箭头函数相当于:

function (x) {
    return x * x;
}

 

箭头函数相当于匿名函数,并且简化了函数定义。箭头函数有两种格式,一种像上面的,只包含一个表达式,连{ ... }return都省略掉了。还有一种可以包含多条语句,这时候就不能省略{ ... }return

x => {
    if (x > 0) {
        return x * x;
    }
    else {
        return - x * x;
    }
}

如果参数不是一个,就需要用括号()括起来:

// 两个参数:
(x, y) => x * x + y * y

// 无参数:
() => 3.14

// 可变参数:
(x, y, ...rest) => {
    var i, sum = x + y;
    for (i=0; i<rest.length; i++) {
        sum += rest[i];
    }
    return sum;
}

如果要返回一个对象,就要注意,如果是单表达式,这么写的话会报错:

// SyntaxError:
x => { foo: x }

因为和函数体的{ ... }有语法冲突,所以要改为:

// ok:
x => ({ foo: x })

this    —— 笔者认为this是重点需要关注的学习目标

箭头函数看上去是匿名函数的一种简写,但实际上,箭头函数和匿名函数有个明显的区别:箭头函数内部的this是词法作用域,由上下文确定。

回顾前面的例子,由于JavaScript函数对this绑定的错误处理,下面的例子无法得到预期结果:

var obj = {
    birth: 1990,
    getAge: function () {
        var b = this.birth; // 1990
        var fn = function () {
            return new Date().getFullYear() - this.birth; // this指向window或undefined
        };
        return fn();
    }
};

现在,箭头函数完全修复了this的指向,this总是指向词法作用域,也就是外层调用者obj

var obj = {
    birth: 1990,
    getAge: function () {
        var b = this.birth; // 1990
        var fn = () => new Date().getFullYear() - this.birth; // this指向obj对象
        return fn();
    }
};
obj.getAge(); // 25

如果使用箭头函数,以前的那种hack写法:

var that = this;

就不再需要了。

由于this在箭头函数中已经按照词法作用域绑定了,所以,用call()或者apply()调用箭头函数时,无法对this进行绑定,即传入的第一个参数被忽略:

var obj = {
    birth: 1990,
    getAge: function (year) {
        var b = this.birth; // 1990
        var fn = (y) => y - this.birth; // this.birth仍是1990
        return fn.call({birth:2000}, year);
    }
};
obj.getAge(2015); // 25

 -----------------------------------------------------------------------------------------------------------------------------------------------------------------------

接下来笔者通过vue代码进行分析:

<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>vue test </title>
		<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
	</head>
	<body>
		<div id="root">
			<div v-on:click="handleClick">{{msg}}</div>
		</div>

		<script>
			new Vue({
				el:"#root",
				data: {
					msg: "hello world"
				},
				methods: {
					//写法一:(正确写法)
					// handleClick: function(){
					// 	this.msg = "111"
					// 	console.log(this)  //this指向vue实例
					// 	alert(this)

					// 	var fn = ()=>{
					// 		this.msg ="222"
					// 		console.log(this)  //箭头函数中this仍然指向vue实例
					// 	}
					// 	return fn(); 
					// 	
					// }
					

					//写法二:
					// handleClick: function(){
					// 	this.msg = "111"
					// 	console.log(this)  //this指向vue实例
					// 	alert(this)

					// 	var fn = function(){
					// 		this.msg ="222"
					// 		console.log(this)  //this指向window
					// 	}
					// 	return fn(); 
					// }
					//因此写法二正确的应该改为:
					handleClick: function(){
						var _this = this  
						this.msg = "111"
						console.log(this)  //this指向vue实例
						alert(this)

						var fn = function(){
							_this.msg ="222"
							console.log(_this)  //_this仍然指向vue实例
						}
						return fn(); 
					}
					
					
					//写法三:(错误写法)
					// handleClick: ()=>{
					// 	console.log(this)   //this指向window (所以一般不在最外层直接用箭头函数)
					// }

					//---总结---
					//箭头函数一般用于函数嵌套时,防止this指向变化,在箭头函数
					//中this的指向一直是外层对象,即廖雪峰大神说的“箭头函数完全
					//修复了this的指向,this总是指向词法作用域,也就是外层调用者obj”
				}
			})
		</script>

	</body>
</html>

可以自行测试,对比调试输出结果。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值