es6 学习笔记(一)箭头函数

由于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)

将其改写成普通函数可以很快理解。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值