箭头函数有两个好处。☕

1.他们比传统函数表达式简洁。

const arr = [1, 2, 3];
const squares = arr.map(x => x * x); // 传统函数表达式:
const squares = arr.map(function (x) { return x * x });

2.箭头函数不会绑定关键字this,我们不需要用bind()或者that = this这种方法了

function UiComponent() {
const button = document.getElementById('myButton');
button.addEventListener('click', () => {
console.log('CLICK');
this.handleClick(); // this不再是button
});
}

和this同样没有被箭头函数绑定的参数有

  • arguments
  • super
  • this
  • new.target

例如:

function foo() {
setTimeout( () => {
console.log("args:", arguments);
},100);
} foo( 2, 4, 6, 8 );
// args: [2, 4, 6, 8]

=>箭头函数并没有绑定 arguments,所以它会以 foo() 的 arguments 来取而代之,而 super 和 new.target 也是一样的情况

传统的函数不好的地方在于有一些非方法的函数,劫持了this

在JavaScript中,传统函数有3种角色:

1.非方法函数

2.方法

3.构造函数

这三种函数在使用中会有角色冲突,角色2、3的函数含有他们自己的this指向,但是角色1会对this进行劫持

你可以看这段传统JS代码:

function Prefixer(pp) {
this.prefix = pp;
}
Prefixer.prototype.prefixArray = function (arr) { // (A)
return arr.map(function (x) { // (B)
// 无法正常工作:
return this.prefix + x; // (C)
});
};
var pre = new Prefixer('Hi ');
pre.prefixArray(['Joe', 'Alex']);//TypeError: Cannot read property 'prefix' of undefined

在C行,我们希望访问this.prefix,但是却无法访问,因为this在非方法函数里是undefined,所以我们会得到报错。

在ECMAScript5中,有三种办法可以绕过这个问题:

方案1 that = this

function Prefixer(prefix) {
this.prefix = prefix;
}
Prefixer.prototype.prefixArray = function (arr) {
var that = this; // (A)
return arr.map(function (x) {
return that.prefix + x;
});
}; var pre = new Prefixer('Hi ');
pre.prefixArray(['Joe', 'Alex']); //[ 'Hi Joe', 'Hi Alex' ]

方案2 直接指定this的值

一部分数组方法会提供一个额外的参数值来修改this,注意A行

function Prefixer(prefix) {
this.prefix = prefix;
}
Prefixer.prototype.prefixArray = function (arr) {
return arr.map(function (x) {
return this.prefix + x;
}, this); // (A)
};

方案3 绑定this

你可以使用bind()方法来告诉函数是谁调用的

function Prefixer(prefix) {
this.prefix = prefix;
}
Prefixer.prototype.prefixArray = function (arr) {
return arr.map(function (x) {
return this.prefix + x;
}.bind(this)); // (A)
};

ECMAScript6 方案:箭头函数

箭头函数的工作方式很像方案3,但箭头函数压根不会修改this的作用域,而且你不需要给正常的函数加绑定。

下面是用了箭头函数后的代码:

function Prefixer(prefix) {
this.prefix = prefix;
}
Prefixer.prototype.prefixArray = function (arr) {
return arr.map((x) => {
return this.prefix + x;
});
};

如果完全用ES6写这段代码,可以写成这样,可以用一个类和一个更节省的方法写函数:

class Prefixer {
constructor(prefix) {
this.prefix = prefix;
}
prefixArray(arr) {
return arr.map(x => this.prefix + x); // (A)
}
}

在A行,我们通过箭头函数省略了一些字符

  • 如果函数只有一个参数(x),那么可以省略括号
  • 如果函数体只有一个表达式,那么可以省略return

箭头函数语法

参数:

    () => { ... } // 没有参数
x => { ... } // 一个参数
(x, y) => { ... } // 多个参数

函数体:

x => { return x * x }  // 语句块
x => x * x // 表达式,和上一行作用相同

如果函数体是一个表达式,会隐式返回结果,对比一下:

const squares = [1, 2, 3].map(function (x) { return x * x });
const squares = [1, 2, 3].map(x => x * x);

单个参数时括号可以省略

只有一个函数参数的时候,才可以省略小括号:

[1,2,3].map(x => 2 * x) //[ 2, 4, 6 ]

如果有多个参数的时候,就必须加上小括号:

[[1,2], [3,4]].map(([a,b]) => a + b) //[ 3, 7 ]

当你使用ES6函数参数默认值的时候也必须加括号:

[1, undefined, 3].map((x='yes') => x) //[1, yes', 3 ]

箭头函数的优先级比较低

如果你把箭头函数当成一个运算符的话,它会有比较低的优先级。

所以当箭头函数和其他运算符相遇时,其他运算符通常会赢。

例如下面示例,箭头函数和条件表达式挨在一起了:

const f = x => (x % 2) === 0 ? x : 0;

换句话说等同于下面的语句:

const f = x => ((x % 2) === 0 ? x : 0);

如果想提高箭头函数的优先级,可以使用括号括住函数,让函数返回结果作为条件:

const f = (x => ((x % 2) === 0)) ? x : 0;

另一方面,当你使用使用typeof这样的表达式作为函数体时,不需要添加括号

const f = x => typeof x;

关于箭头函数换行

es6禁止参数定义和箭头之间的换行符

const func1 = (x, y) // SyntaxError
=> {
return x + y;
};
const func2 = (x, y) => // OK
{
return x + y;
};
const func3 = (x, y) => { // OK
return x + y;
}; const func4 = (x, y) // SyntaxError
=> x + y;
const func5 = (x, y) => // OK
x + y;

在参数中换行是可以的:

const func6 = ( // OK
x,
y
) => {
return x + y;
};

关于箭头函数的函数体

函数体内只有一个表达式是可以省略大括号的:

asyncFunc.then(x => console.log(x));

但是声明必须放在大括号中:

asyncFunc.catch(x => { throw x });

返回对象变量

如果想让函数返回一个花括号对象,就要加小括号:

const f1 = x => ({ bar: 123 });
f1();//{ bar: 123 }

不然的话,程序会认为这是一个块级作用域

const f2 = x => { bar: 123 };
> f2() //undefined

立即调用的箭头函数

还记得立即调用函数表达式(IIFE)吗? 它们如下所示,用于模拟ECMAScript 5中的块范围和值返回块:

(function () { // open IIFE
// inside IIFE
})(); // close IIFE

你也可以用箭头函数模拟:

(() => {
return 123
})()

提取方法

<a id="myButton">按钮</a>
<script type="text/javascript" src="js/babel.min.js"></script>
<script type="text/babel">
class KK {
constructor() {
var myButton = document.getElementById('myButton');
myButton.addEventListener('click', event => this.handleEvent(event));
//es5 myButton.addEventListener('click', this.handleEvent.bind(this));
} handleEvent(event) {
console.log(event);
}
} var kk = new KK();
</script>

箭头函数还可以用于参数指定技巧

比如使用array.filter需要传入函数,而且需要指定this对象为bs,只能通过额外参数来指定

const as = new Set([1, 2, 3]);
const bs = new Set([3, 2, 4]);
const intersection = [...as].filter(bs.has, bs);// [2, 3]

可以用箭头函数优化写法:

const as = new Set([1, 2, 3]);
const bs = new Set([3, 2, 4]);
const intersection = [...as].filter(a => bs.has(a)); // [2, 3]

部分求值

以前可以利用bind来产生一个新的函数来求值,但是尴尬的是第一个参数必须要传入undefined,这变得难以理解:

function add(x, y) {
return x + y;
}
const plus1 = add.bind(undefined, 1);
console.log(plus1(2));//

如果用箭头函数,就变得容易理解:

const plus1 = y => add(1, y);

箭头函数和普通函数对比

1.箭头函数中不会干涉下列关键字:super, this, new.target

2.箭头函数没有构造函数:常规函数有Construct和函数属性,而箭头函数没有,所以 new (() => {}) 会报错

除了以上两点,箭头函数和普通函数没有什么区别,typeof和instanceof输出的结果相同:

typeof (() => {}) //'function'
() => {} instanceof Function //true typeof function () {} //'function'
function () {} instanceof Function //true

参考资料:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

es6 箭头函数(arrow function) 学习笔记的更多相关文章

  1. ES6箭头函数Arrow Function

    果然,隔了很长时间都没有来博客园上逛了...... 前一段时间一直在忙我们参加的一个比赛,转眼已经好久没有来逛过博客园了,果然还是很难坚持的...... 今天总算还是想起来要过来冒个泡,强行刷一波存在 ...

  2. [ES6系列-02]Arrow Function:Whats this?(箭头函数及它的this及其它)

    [原创] 码路工人 大家好,这里是码路工人有力量,我是码路工人,你们是力量. 如果没用过CSharp的lambda 表达式,也没有了解过ES6,那第一眼看到这样代码什么感觉? /* eg.0 * fu ...

  3. 深入浅出ES6(七):箭头函数 Arrow Functions

    作者 Jason Orendorff  github主页  https://github.com/jorendorff 箭头符号在JavaScript诞生时就已经存在,当初第一个JavaScript教 ...

  4. 箭头函数 Arrow Functions/////////////////////zzz

    箭头符号在JavaScript诞生时就已经存在,当初第一个JavaScript教程曾建议在HTML注释内包裹行内脚本,这样可以避免不支持JS的浏览器误将JS代码显示为文本.你会写这样的代码: < ...

  5. ES6 箭头函数(Arrow Functions)

    ES6 箭头函数(Arrow Functions) ES6 可以使用 "箭头"(=>)定义函数,注意是函数,不要使用这种方式定义类(构造器). 一.语法 具有一个参数的简单函 ...

  6. [译]ES6箭头函数和它的作用域

    原文来自我的前端博客: http://www.hacke2.cn/arrow-functions-and-their-scope/ 在ES6很多很棒的新特性中, 箭头函数 (或者大箭头函数)就是其中值 ...

  7. ES6箭头函数和它的作用域

    原文来自我的前端博客: http://www.hacke2.cn/arrow-functions-and-their-scope/ http://es6rocks.com/2014/10/arrow- ...

  8. ES6 箭头函数你正确使用了吗

    ES6 箭头函数你正确使用了吗 博客说明 文章所涉及的资料来自互联网整理和个人总结,意在于个人学习和经验汇总,如有什么地方侵权,请联系本人删除,谢谢! 说明 在ES6中允许使用"箭头&quo ...

  9. es6箭头函数讲解

    es6箭头函数的用法 箭头函数是es6的一种函数的简写方法. 如下: var f = v = > v; //等同于 var f = function(v){ return v; } var su ...

随机推荐

  1. 微信jsSDK公众号开发时网页提示 invalid signature错误的解决方法

    微信公众号开发jsSDK,链接地址不能加?参数,可以通过#传递参数. 不然.页面wx.ready()时就会报错,用 wx.error(function (res) { alert("接口验证 ...

  2. 从C#到TypeScript - 接口

    总目录 从C#到TypeScript - 类型 从C#到TypeScript - 高级类型 从C#到TypeScript - 变量 从C#到TypeScript - 接口 从C#到TypeScript ...

  3. 使用 position:sticky 实现粘性布局

    如果问,CSS 中 position 属性的取值有几个?大部分人的回答是,大概是下面这几个吧? { position: static; position: relative; position: ab ...

  4. Match类解析

    Matcher类:使用Matcher类,最重要的一个概念必须清楚:组(Group),在正则表达式中()定义了一个组,由于一个正则表达式可以包含很多的组,所以下面先说说怎么划分组的,以及这些组和组的下标 ...

  5. 简单了解Hibernate

    orm 对象 object 关系relational映射 mppingorm对象关系映射hibernate 框架是什么?很简单 持久化框架  他轻松的封装了jdbc那些繁琐的操作什么是持久化?持久化就 ...

  6. 【WC2015】混淆与破解 (Goldreich-Levin 算法)

    这个嘛= =直接贴VFK的题解就行了吧,感觉自己还是差别人太多 http://vfleaking.blog.uoj.ac/blog/104 讲得挺明白了的说,但还是挺难理解的说,中间实现部分简直不要太 ...

  7. BZOJ 1033: [ZJOI2008]杀蚂蚁antbuster(模拟)

    坑爹的模拟题QAQ DEBUG多了1kb QAQ 按题意做就行了 注意理解题意啊啊啊啊 尼玛输出忘换行wa了3次QAQ CODE: #include<cstdio>#include< ...

  8. Hadoop学习笔记:使用Mrjob框架编写MapReduce

    1.mrjob介绍 一个通过mapreduce编程接口(streamming)扩展出来的Python编程框架. 2.安装方法 pip install mrjob,略.初学,叙述的可能不是很细致,可以加 ...

  9. 《经久不衰的Spring框架:Spring+SpringMVC+MyBatis 整合》

    前言 主角即Spring.SpringMVC.MyBatis,即所谓的SSM框架,大家应该也都有所了解,概念性的东西就不写了,有万能的百度.之前没有记录SSM整合的过程,这次刚刚好基于自己的一个小项目 ...

  10. 【转】Tomcat源代码阅读系列

    在IntelliJ IDEA 和 Eclipse运行tomcat 7源代码(Tomcat源代码阅读系列之一) Tomcat总体结构(Tomcat源代码阅读系列之二) Tomcat启动过程(Tomcat ...