箭头表达式

1. 历史

从一开始箭头就是 JavaScript 的一部分,在第一个 JavaScript 中就建议将内联的脚本代码包裹在 HTML 的注释中,这可以防止那些不支持 JavaScript 的浏览器错误滴将你的代码显示为明文
	<script language="javascript"> 
	<!-- 
	document.bgColor = "brown"; // red //
	 --> 
	 </script>
	 
	<!-- 单行注释
	--> goes to 操作符
	<= 小于等于操作符
	=> ???
	

2. 单行箭头表达式:
	1 var foo = (arg1,arg2) => arg1 + arg2;
	2 //上述表达式相当于
	3 var foo = function (arg1, arg2) { return arg1 + arg2; };
	

2. 多行箭头表达式(必须使用{}大括号):
	1 var foo = (arg1, agr2) => {
	2     return arg1 + agr2;
	3 }
	4 
	5 //以上表达式相当于
	6 var foo = function (arg1, arg2) {
	7     return arg1 + arg2;
	8 };
	

3. 无参数:
	1 var foo = () => {}
	2 
	3 //以上表达式相当于
	4 var foo = function () {}
	

4. 一个参数(无需使用()小括号):
	1 var foo = arg => {
	2   return arg*arg;    
	3 }
	4 
	5 //以上表达式相当于
	6 var foo = function (arg) {
	7    return arg*arg;  
	8 }
	

5.
	var array = [1, 2, 3];
	
	//传统写法
	array.forEach(function(v, i, a) {
		console.log(v);
	});
	
	//ES6
	array.forEach(v = > console.log(v));
	


5. this 指针
	{ 
	... 
	addAll: function addAll(pieces) { 
		var self = this; 
		_.each(pieces, function (piece) { 
			self.add(piece); 
		}); 
	}, 
	... 
	}
	

内部函数并没有继承外部函数的 this,在内部函数中,this 的值可能是 window 或 undeinfed。这里使用了 self这个临时变量来将外部函数中的 this 值传递到内部函数中(也可以使用 .bind(this)的方式,但两个方式都不是特别漂亮

在 ES6 中,如果你遵循以下规则,那么你就再也不会写出上面的 hack 代码了:

a. 调用对象的方法时,使用 object.method() 语法,这样将通过调用者为这些方法提供一个有意义的 this 值

b. 其他情况请使用箭头函数
	// ES6 
	{ 
	... 
	addAll: function addAll(pieces) { 
		_.each(pieces, piece => this.add(piece)); 
		}, 
	... 
	}
	

内部函数中使用了箭头函数,所以将从闭包区域继承 this 的值。

猜你喜欢

转载自37235798.iteye.com/blog/2400110