Foreword
This article excerpted from "understanding ECMAScript6" Chapter III - function, the main contents include: the difference with the traditional function of the arrow function, syntax, create a function to perform functions using the arrow, the arrow function of this immediately, and so on
Difference function and the conventional function arrow
- No this, super, arguments, nor new.target binding : their values are determined by where the closest non-arrow function
- Can not be invoked new : arrow function does not [[constructor]] method, can not be invoked as a constructor is new
- No prototype : no prototype property
- You can not change this : the value of this constant is decided by the containing function, throughout the life cycle of a function of its value
- No arguments object : arrow function does not bind arguments, parameters, or parameters have to rely on the remaining parameters to access functions
- Not allowed to repeat the parameter : Whether strict mode or non-strict mode, do not allow duplicate the parameter
grammar
When a single parameter, omit the parentheses
|
|
A number of parameters, no parameters, need brackets
|
|
|
|
Creating empty function
|
|
Returns the object literal: the object literal wrapped in parentheses, brackets represent a literal is not the function body
|
|
注意:上面的箭头函数都是没有使用花括号的,这种情况下js引擎默认添加了return。而使用花括号后,需要手动添加return语句,如果没加,函数将不返回值
创建立即执行函数
使用传统函数时,(function(){})()、(function(){}())都可以,而箭头函数只支持(() => {})();
|
|
没有this绑定
传统函数中的this可以被改变,其值取决于调用该函数时的上下文
|
|
使用bind()方法
|
|
箭头函数没有this绑定,this只能通过查找作用域来确定。如果箭头函数被包含在一个非箭头函数内,那么this就与该函数的this相等;否则,this值为undefined
|
|
注意:由于箭头函数的this值由包含它的函数决定,因此不能使用call、apply、bind方法来改变this值
没有arguments对象
虽然箭头函数没有自己的arguments对象,但是可以访问包含它的函数的arguments对象
|
|