由于es6的新增语法很多,就想着写点东西,方便自己记下来,也可以把学习过程中遇到的一些问题跟大家分享。(第一次写博客,有什么排版的问题,请见谅)
参考链接: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
setInterval(() => 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)
将其改写成普通函数可以很快理解。