【问题标题】:'this' is undefined in Javascript arrow function [duplicate]'this'在Javascript箭头函数中未定义[重复]
【发布时间】:2017-03-02 17:24:21
【问题描述】:

在Javascript事件的回调函数中,this是被点击的元素:

  document.querySelector('#my-element').addEventListener('click', function() {
    console.log(this);  // <div id="my-element">
  });

但是,当我使用 ES6 箭头函数时,this 变成了undefined

  document.querySelector('#my-element').addEventListener('click', () => {
    console.log(this);  // undefined
  });

有人可以解释一下这种行为吗?

【问题讨论】:

标签: javascript ecmascript-6 this dom-events arrow-functions


【解决方案1】:

箭头函数在调用时不会导致this 被绑定。它在封闭的词法范围内具有任何价值。在您的情况下,这意味着封闭范围内的thisundefined

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 2021-04-22
    • 1970-01-01
    • 2023-03-15
    • 2017-12-06
    • 2021-09-17
    相关资源
    最近更新 更多