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

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

    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 命令
  • 箭头函数不适合定义结合动态上下文的回调函数(事件绑定函数),由于箭头函数在声明的时候会绑定静态上下文java

    const button = document.querySelector('button'); button.addEventListener('click', () => { this.textContent = 'Loading...'; }); // this 并非指向预期的 button 元素,而是 window
相关文章
相关标签/搜索