this 关键字如何用于函数表达式和箭头函数?

How does the this keyword work for an function expression and arrow function?

最近我一直在阅读 John Resig 的 'The Secrets of JavaScript Ninja' 并且我已经看到了清单 4.10,即 "Binding a Specific Context to a Function",其中的代码旨在在单击按钮时打印。 作者表明,只有使用箭头函数而不是普通函数表达式,代码才会 运行 成功。为什么代码不能与函数表达式一起正常工作? this 关键字如何工作?

下面是带有函数表达式的代码:

function Button() {
  this.clicked = false;
  this.click = function() {
    this.clicked = true;
    if (button.clicked) {
      "The button has been clicked"
    };
  };
}
var button = new Button();
var elem = document.getElementById("test");
elem.addEventListener("click", button.click);
<button id="test">Click Me!</button>

这是带有箭头功能的代码(完美运行):

function Button() {
  this.clicked = false;
  this.click = () => {
    this.clicked = true;
    if (button.clicked) {
      console.log("The button has been clicked");
    }
  };
}
var button = new Button();
var elem = document.getElementById("test");
elem.addEventListener("click", button.click);
<button id="test">Click Me!</button>

您可以运行以下代码。

function Button1() {
  this.clicked = false;
  this.click = function() {
    this.clicked = true;
 console.log('bt1',this);
    if (button1.clicked) {
      console.log("The button has been clicked 1"); 
    };
  };
}
function Button2() {
  this.clicked = false;
  this.click = () => {
    this.clicked = true;
 console.log('bt2',this);
    if (button2.clicked) {
      console.log("The button has been clicked 2");
    }
  };
}

var button1 = new Button1();
var button2 = new Button2();
var elem = document.getElementById("test");
elem.addEventListener("click", button1.click);
elem.addEventListener("click", button2.click);
<button id="test">Click Me!</button>

'this'只是正常功能中的一个HTML。

如果你使用 'button1.click.bind(button1)',将 运行 成功。