码迷,mamicode.com
首页 > 其他好文 > 详细

箭头函数适用场景及需要注意的地方

时间:2018-02-10 14:03:40      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:全局   foo   prototype   地方   回调函数   new   函数定义   list   识别   

  • 箭头函数适合于无复杂逻辑或者无副作用的纯函数场景下,例如:用在 map、reduce、filter 的回调函数定义中
  • 箭头函数的亮点是简洁,但在有多层函数嵌套的情况下,箭头函数反而影响了函数的作用范围的识别度,这种情况不建议使用箭头函数
  • 箭头函数要实现类似纯函数的效果,必须剔除外部状态。所以箭头函数不具备普通函数里常见的 this、arguments 等,当然也就不能用 call()、apply()、bind() 去改变 this 的指向
  • 箭头函数不适合定义对象的方法(对象字面量方法、对象原型方法、构造器方法),因为箭头函数没有自己的 this,其内部的 this 指向的是外层作用域的 this

    const json = {
        bar: 1,
        fn: () => console.log(this.bar)
    };
    
    json.fn();  //-> undefined
    // this 并不是指向 json 这个对象,而是再往上到达全局作用域
    function Foo() {
        this.bar = 1;
    }
    Foo.prototype.fn = () => console.log(this.foo);
    
    const foo = new Foo();
    foo.fn();  //-> undefined
    // this 并不是指向 Foo,根据变量查找规则,回溯到了全局作用域
    const Message = (text) => {  
        this.text = text;
    };
    var helloMessage = new Message(‘Hello World!‘);  
    console.log(helloMessage.text); //-> Message is not a constructor
    // 不可以当作构造函数,也就是说,不可以使用 new 命令
  • 箭头函数不适合定义结合动态上下文的回调函数(事件绑定函数),因为箭头函数在声明的时候会绑定静态上下文

    const button = document.querySelector(‘button‘);
    button.addEventListener(‘click‘, () => {  
        this.textContent = ‘Loading...‘;
    });
    // this 并不是指向预期的 button 元素,而是 window

箭头函数适用场景及需要注意的地方

标签:全局   foo   prototype   地方   回调函数   new   函数定义   list   识别   

原文地址:https://www.cnblogs.com/dujishi/p/8438420.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!