# 箭头函数

# 定义。

箭头函数是 ES6 出现的一种语法,它有自己的特性,可以看作是函数表达式。(主要不是 function 这种函数式写法都属于表达式).

# 用法

var foo = (a) => { return a};

var foo = (a) => a;
var foo = a => a;

都是一样的。这个只是它的写法。

函数返回函数的写法。
var bar = (a) => (b) => a + b;
这种写法写一个偏函数就简单多了
var bar = (fn, ...args) => (...moreArgs) => fn(...args, ...moreArgs);

上面知识它写法上带来的简单,真正带来的方便是它的特性。

# 没有自己的 this

this 是在函数执行过程中确定的。所以函数是有 this 的。 但是 箭头函数是没有 this 的,但是我们可以在它里面用词法作用域外的 this 指向。

function foo() {
    console.log(this);  // window;
}
foo();

var bar = () => {console.log(this)};  // window
bar();

虽然都是指向 window, 但是寻找过程是不一样的。

foo 的 this 是本身属于 foo 函数内部的,只因是默认绑定。

bar 的 this 是通过找到全局作用域下的 this。才确定是 window。

好处,不需要我们单独的保存外面的 this 指向。

function foo() {
    setTimeout(() => {
        console.log(this);
    }, 500);
}

# 没有 arguments

箭头函数中是没有 arguments 的。

给我们带来的好处就是我们在做一个装饰器的时候将非常的方便。

我们可以直接进行转发一个调用。
function foo(fn) {
    return () => {
        fn.apply(this, arguments);
    };
}

# 不能够被 new

我们从 new 的原理来讲, 第三部需要调用构造函数并传入当前对象。使用箭头函数来当作构造函数的话,都没有 this。所以不能被 new。

# 不能够使用 super

super 的原理也是 this 的一个体现,我们使用过 super,使得继承父构造函数。那么父构造函数也得使用 this 来保持同步。

# Babel 转译

ES5

const obj = {
    getArrow() {
        return () => {
            console.log(this);
        }
    }
}

ES6

var obj = {
    getArrow = function getArrow() {
        var _this = this;
        return function () {
            console.log(_this);
        }
    }
}