onclick 事件以不同方式执行相同的功能

onclick event executing the same function differently

我有一个测试功能:

function test(element) {
    console.log(element.id);
    console.log(element);
}

我想在按下按钮 <button id="testbtn">afsdasd</button> 时用作回调。如果我这样做:

document.getElementById('testbtn').onclick = () => { 
    test(this); 
};

我得到以下输出: 但是,如果我这样做:

document.getElementById('testbtn').onclick = function() { 
    test(this); 
};

输出不同: 为什么?我以为两个版本完全一样?

第一个是箭头函数,第二个是正则函数。箭头函数没有自己的 this 绑定,因此它们将在下一个外部词法范围内搜索 this。在您的情况下,箭头函数的封闭词法范围是 Window 对象。

An arrow function does not have its own this. The this value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching for this which is not present in current scope, an arrow function ends up finding the this from its enclosing scope. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions