Javascript 如何使用正则函数调用此参数?

Javascript 如何使用正则函数调用此参数?,javascript,this,arrow-functions,Javascript,This,Arrow Functions,我试图用forEach()方法调用divRepo元素,但由于这个参数,我感到困惑。我可以将this参数与箭头函数一起使用。但是,当我将this参数与正则函数一起使用时,会得到一个未定义的文本作为输出。是否可以使用常规函数调用divRepo? 谢谢 具有常规功能 类用户界面{ 构造函数(){ this.divRepo=document.querySelector(“repos”); } showUserRepositories(repos){ 回购forEach(功能(回购){ console.l

我试图用forEach()方法调用divRepo元素,但由于这个参数,我感到困惑。我可以将this参数与箭头函数一起使用。但是,当我将this参数与正则函数一起使用时,会得到一个未定义的文本作为输出。是否可以使用常规函数调用divRepo? 谢谢

具有常规功能

类用户界面{
构造函数(){
this.divRepo=document.querySelector(“repos”);
}
showUserRepositories(repos){
回购forEach(功能(回购){
console.log(this)//输出:未定义
this.divRepo.innerHTML=`
`;
});
}
}
带箭头功能

类用户界面{
构造函数(){
this.divRepo=document.querySelector(“repos”);
}
showUserRepositories(repos){
回购外汇((回购)=>{
log(this)//输出:UI{divRepo:div#repos}
this.divRepo.innerHTML=`
`;
});
}

}

不清楚为什么您不能使用箭头功能,因为它是为解决这类问题而设计的。如果出于某种原因必须使用非箭头函数,一个选项是使用
forEach
的第二个参数,这将建立
上下文:

repos.forEach(function (repo) {
  // ...
}, this);
还有其他替代方法,例如在闭包中捕获对
的引用:

const that = this;
repos.forEach(function (repo) {
  // ...
  console.log(that);
});
…或绑定:

const processRepo = function (repo) {
  // ...
};
repos.forEach(processRepo.bind(this));

您可以将
存储在
中\u此
或在函数上使用
绑定
,但有什么意义?只需使用箭头函数。我是一个有点好奇的人,我正在考虑其他解决方案…谢谢Jacob
const processRepo = function (repo) {
  // ...
};
repos.forEach(processRepo.bind(this));