diff --git a/docs/arrow.md b/docs/arrow.md new file mode 100644 index 0000000..b64ebfc --- /dev/null +++ b/docs/arrow.md @@ -0,0 +1,113 @@ +# 箭头函数 + +## 定义 + +ES6允许使用“箭头”(=>)定义函数。 + +```javascript + +var f = v => v; + +``` + +上面的箭头函数等同于: + +```javascript + +var f = function(v) { + return v; +}; + +``` + +如果箭头函数不需要参数或需要多个参数,就使用一个圆括号代表参数部分。 + +```javascript + +var f = () => 5; +// 等同于 +var f = function (){ return 5 }; + +var sum = (num1, num2) => num1 + num2; +// 等同于 +var sum = function(num1, num2) { + return num1 + num2; +}; + +``` + +如果箭头函数的代码块部分多于一条语句,就要使用大括号将它们括起来,并且使用return语句返回。 + +```javascript + +var sum = (num1, num2) => { return num1 + num2; } + +``` + +由于大括号被解释为代码块,所以如果箭头函数直接返回一个对象,必须在对象外面加上括号。 + +```javascript + +var getTempItem = id => ({ id: id, name: "Temp" }); + +``` + +##实例:回调函数 + +箭头函数的一个用处是简化回调函数。 + +```javascript + +// 正常函数写法 +[1,2,3].map(function (x) { + return x * x; +}); + +// 箭头函数写法 +[1,2,3].map(x => x * x); + +``` + +另一个例子是 + +```javascript + +// 正常函数写法 +var result = values.sort(function(a, b) { + return a - b; +}); + +// 箭头函数写法 +var result = values.sort((a, b) => a - b); + +``` + +## 注意点 + +箭头函数有几个使用注意点。 + +- 函数体内的this对象,绑定定义时所在的对象,而不是使用时所在的对象。 +- 不可以当作构造函数,也就是说,不可以使用new命令,否则会抛出一个错误。 +- 不可以使用arguments对象,该对象在函数体内不存在。 + +关于this对象,下面的代码将它绑定定义时的对象。 + +```javascript + +var handler = { + + id: "123456", + + init: function() { + document.addEventListener("click", + event => this.doSomething(event.type), false); + }, + + doSomething: function(type) { + console.log("Handling " + type + " for " + this.id); + } +}; + +``` + +上面代码的init和doSomething方法中,都使用了箭头函数,它们中的this都绑定handler对象。否则,doSomething方法内部的this对象就指向全局对象,运行时会报错。 diff --git a/docs/reference.md b/docs/reference.md index b3b3902..5ad5c6d 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -12,6 +12,7 @@ - Nick Fitzgerald, [Destructuring Assignment in ECMAScript 6](http://fitzgeraldnick.com/weblog/50/) - Nicholas C. Zakas, [Understanding ECMAScript 6 arrow functions](http://www.nczonline.net/blog/2013/09/10/understanding-ecmascript-6-arrow-functions/) +- Jack Franklin, [Real Life ES6 - Arrow Functions](http://javascriptplayground.com/blog/2014/04/real-life-es6-arrow-fn/) ## Generator diff --git a/sidebar.md b/sidebar.md index bea089b..e4446e8 100644 --- a/sidebar.md +++ b/sidebar.md @@ -7,6 +7,7 @@ ## 目录 - [前言](#README) - [ECMAScript 6简介](#docs/intro) +- [箭头函数](#docs/arrow) - [Iterator:遍历器](#docs/iterator) - [Generator函数](#docs/generator) - [Promise对象](#docs/promise) @@ -15,3 +16,4 @@ ## 其他 - [源码](http://github.com/ruanyf/es6tutorial/) - [修订历史](https://github.com/ruanyf/es6tutorial/commits/gh-pages) +- [反馈意见](https://github.com/ruanyf/es6tutorial/issues)