美文网首页
箭头函数

箭头函数

作者: 珍珠林 | 来源:发表于2017-04-30 11:48 被阅读0次

    箭头函数语法

    单一参数的单行箭头函数

    const fn = foo => `${foo} world` // means return `foo + ' world'`
    

    这是箭头函数最简洁的形式,常见于作用简单的处理函数:

    let array = ['a', 'bc', 'def', 'ghij'];
    array = array.filter(item => item.length >= 2); //> bc, def, ghij
    

    多参数的单行箭头函数

    const fn = (foo, bar) => foo + bar;
    

    比如数组的排序:

    let array = ['a', 'bc', 'def', 'ghij'];
    array = array.sort((a, b) => a.length < b.length); //=> ghij, def, bc, a
    

    多行箭头函数

    // 单一参数
    foo => {
        return `${foo} world`;
    }
    
    // 多参数
    (foo, bar) => {
        return boo + bar;
    }
    

    this穿透

    箭头函数在ES2015中不单单只是作为一种语法糖出现,它可以将函数内部的this延伸至上一层作用域中,即上一层的上下文会穿透到内层的箭头函数中。用代码来解释:

    const obj = {
        hello: 'world',
        foo() {
            // this
            const bar = () => this.hello;
            return bar;
        }
    };
    
    window.hello = 'ES6';
    window.bar = obj.foo();
    window.bar() //=> 'world'
    

    如果用Babel等ES2015编译工具将其转换为ES5的代码,obj.foo函数如下:

    // ...
    foo() {
        var that = this;
        var bar = function() {
            return that.hello;
        };
        return bar;
    }
    

    为什么要赋予箭头函数这样的特性呢?只要有ECMAScript编程经验的都知道,在单行匿名函数中,如果this指向的是该函数的上下文,就会不符合直观的语义表达。

    箭头函数对上下文的绑定是强制性的,无法通过apply或call方法改变。

    因为箭头函数绑定上下文的特性,故不能随意在顶层作用域中使用箭头函数。同样的,在箭头函数中没有arguments、callee、caller等对象。

    相关文章

      网友评论

          本文标题:箭头函数

          本文链接:https://www.haomeiwen.com/subject/vgzttxtx.html