es6 学习笔记(一)箭头函数
2017-03-23 14:44
597 查看
由于es6的新增语法很多,就想着写点东西,方便自己记下来,也可以把学习过程中遇到的一些问题跟大家分享。(第一次写博客,有什么排版的问题,请见谅)
参考链接:http://es6.ruanyifeng.com/#docs/let
1.箭头函数
es6新增的箭头函数可以说是我最喜欢的东西了,最喜欢这种风骚的写法。
箭头函数的基本用法很简单:
箭头函数最需要注意的地方: this
箭头函数本身没有自己的this,导致函数内部的this 就是外部代码块的this。所以,箭头函数不可以使用New。
使用aop的一个例子可以加深理解:
这里before和after中的第一层function不能使用箭头函数。原因是一但使用箭头函数,第二层function中的this就指向了全局。
阮神还写了一个管道机制的例子:
刚开始看过去可能会有点懵逼,其实还是挺简单的:
将其改写成普通函数可以很快理解。
参考链接:http://es6.ruanyifeng.com/#docs/let
1.箭头函数
es6新增的箭头函数可以说是我最喜欢的东西了,最喜欢这种风骚的写法。
箭头函数的基本用法很简单:
var f = (x,y) => x+y; //等于 var f = function(x,y) { return x+y; };
箭头函数最需要注意的地方: this
function Timer() { this.s1 = 0; this.s2 = 0; // 箭头函数 this指向timer setInt 4000 erval(() => this.s1++, 1000); // 普通函数 this指向全局(node中似乎不是这样的) setInterval(function () { this.s2++; }, 1000); } var timer = new Timer(); setTimeout(() => console.log('s1: ', timer.s1), 3100);//3 setTimeout(() => console.log('s2: ', timer.s2), 3100);//0
箭头函数本身没有自己的this,导致函数内部的this 就是外部代码块的this。所以,箭头函数不可以使用New。
使用aop的一个例子可以加深理解:
function test(){ alert(2) } Function.prototype.before = function(fn){ return () =>{ fn();//alert(1); this.call(this); //回调本身 } }; Function.prototype.after=function(fn){ return ()=>{ this.call(this);//回调本身 fn();//alert(3); } }; test .after(()=>alert(3)) .before(()=>alert(1)) ();
这里before和after中的第一层function不能使用箭头函数。原因是一但使用箭头函数,第二层function中的this就指向了全局。
阮神还写了一个管道机制的例子:
const pipeline = (...funcs) => val => funcs.reduce((a, b) => b(a), val); const plus1 = a => a + 1; const mult2 = a => a * 2; const addThenMult = pipeline(plus1, mult2); addThenMult(5)
刚开始看过去可能会有点懵逼,其实还是挺简单的:
const pipeline = function(...funcs){ return function(val){ return funcs.reduce(function(a,b){ return b(a); },val) } } pipeline(plus1, mult2)(5)
将其改写成普通函数可以很快理解。
相关文章推荐
- ECMAScript 学习笔记(2)--ES6新增let、箭头函数理解
- ES6学习笔记之Generator 函数的语法
- es6中箭头函数学习的一个记录
- ES6学习记录之class, extends, super和箭头函数与this
- es6中箭头函数学习的一个记录
- ES6学习------箭头函数
- ES6学习——箭头函数
- ECMAScript 6 学习系列课程 (ES6 箭头函数的使用)
- Javascript学习笔记_箭头函数
- es6中箭头函数学习的一个记录
- ES6学习总结之函数变化(函数默认参数,扩展运算符,箭头函数)
- es6中箭头函数学习的一个记录
- es6中箭头函数学习的一个记录
- es6学习第1天,箭头函数 块级作用域
- react native语法ECMAScript 6 学习笔记----箭头函数和延展操作符
- es6中箭头函数学习的一个记录
- es6中箭头函数学习的一个记录
- es6中箭头函数学习的一个记录
- 笔记:ES6新特性-函数的简写(箭头函数)
- ES6学习6章:函数的扩展(箭头函数)