简体   繁体   English

在 foreach 循环中转换为箭头 function 会导致 TypeError

[英]Conversion to arrow function inside foreach loop results in TypeError

I have this code block that I use to bind an event listener to every anchor tag with a # href.我有这个代码块,用于将事件侦听器绑定到每个带有#的锚标记。 I decided to convert event listener's callback function to an arrow function but while the original code works, the modified one results in an error: TypeError: undefined has no properties .我决定将事件侦听器的回调 function 转换为箭头 function 但是虽然原始代码有效,但修改后的代码会导致错误: TypeError: undefined has no properties I have used arrow callback functions many times before and they do work fine.我以前多次使用过箭头回调函数,它们确实工作得很好。 What makes it break in this instance?是什么让它在这种情况下破裂?

Original code that works:有效的原始代码:

document.querySelectorAll('a[href^="#"]').forEach((anchor) => {
  anchor.addEventListener('click', function (e) {
    e.preventDefault();
    document.querySelector(this.getAttribute('href')).scrollIntoView({
      behavior: 'smooth',
    });
  });
});

Broken arrow callback function:断箭回调function:

document.querySelectorAll('a[href^="#"]').forEach((anchor) => {
  anchor.addEventListener('click', (e) => {
    e.preventDefault();
    document.querySelector(this.getAttribute('href')).scrollIntoView({
      behavior: 'smooth',
    });
  });
});

Edit: I fixed the issue like this but I still cannot figure out how these two are different编辑:我解决了这样的问题,但我仍然无法弄清楚这两者有何不同

document.querySelectorAll('a[href^="#"]').forEach((anchor) => {
  anchor.addEventListener('click', (e) => {
    e.preventDefault();
    anchor.scrollIntoView({
      behavior: 'smooth',
    });
  });
});

Or:或者:

document.querySelectorAll('a[href^="#"]').forEach((anchor) => {
  anchor.addEventListener('click', (e) => {
    e.preventDefault();
    e.target.scrollIntoView({
      behavior: 'smooth',
    });
  });
});

The problem is because the use of this inside your function.问题是因为在你的 function 里面使用了this

According to MDN :根据MDN

An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords .箭头 function 表达式是常规 function 表达式的语法紧凑替代方案,尽管没有自己与 this、arguments、super. 或 new.target 关键字的绑定。

As @Ben Aston already mentioned in the comments you could change this.getAttribute to event.target.getAttribute正如@Ben Aston 在评论中已经提到的,您可以将this.getAttribute更改为event.target.getAttribute

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM