javascript - 为什么 "this"不等于调用该函数的对象?

标签 javascript object events methods window

我有一个附加到 dom 对象的函数。我希望能够从函数内引用 dom 对象,但是当我从事件中调用它时,this不等于正确的事情。

var main = document.getElementById('main');

main.testFunction = () => {
  console.log('this',this);
}

main.addEventListener('click', main.testFunction);

它等于 window 。为什么是这样?如何引用该方法所属的对象?

最佳答案

这是因为您正在使用箭头函数。箭头函数没有自己的 this。使用正常功能就可以了。根据MDN

An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this

var main = document.getElementById('main');
main.testFunction = function() {
  console.log('this',this);
}
main.addEventListener('click', main.testFunction);
<button id="main"> main</button>

其次,当您使用 addEventListener 并传递函数时,附加事件的元素将自动绑定(bind)到给定函数。请参阅代码片段

var main = document.getElementById('main');
function testFunction(){
  console.log('this',this);
}
main.addEventListener('click', testFunction);
<button id="main"> main</button>

如果您想访问箭头函数内的元素,请使用 event.target 而不是 this

var main = document.getElementById('main');
main.testFunction = (e) => {
  console.log('this',e.target);
}
main.addEventListener('click', main.testFunction);
<button id="main"> main</button>

关于javascript - 为什么 "this"不等于调用该函数的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55785661/

相关文章:

IOS UIWebView : How to add listeners to DOM events?

magento - 捕获产品属性更新 massaction 事件

javascript - 为 AWS SDK JavaScript V3 重试设置 customBackoff

ios - 检查数组是否存在于 JSON 文件中 - iOS

android - 按下按钮时连续增加整数值

java - 字符串,运算符“+”的内存已满

javascript - 搜索有关速度/效率的 JSON 对象

javascript - 是否有任何库可以使从字符串创建元素变得容易?

javascript - 将 css 类添加到 DOM 主体的安全且最快的方法

javascript - 如何将字符串转换为大写字母开头