使用它时箭头功能和功能声明之间的区别是什么?

时间:2017-12-13 15:38:34

标签: javascript this arrow-functions function-declaration

我正在使用容器中的按钮尝试使用vanilla JavaScript,我正在尝试使用 this 获取按钮元素并将其记录到控制台。但结果会根据我在click事件上声明函数的方式而改变。

这是HTML代码:

<div class="container">
  <button id="this-button">this</button>
</div>

以下是JavaScript代码:

const containers = document.getElementsByClassName('container');
const thisButton = document.getElementById('this-button');

thisButton.onclick = () => {
  console.log(this);
};

单击按钮时,Window对象将记录到控制台,但如果我更改了函数声明的箭头函数,则这样:

thisButton.onclick = function () {
  console.log(this);
};

按钮元素将记录到控制台 我想知道为什么会发生这种情况,提前谢谢。

0 个答案:

没有答案