如何使用常规函数调用此参数?

how to use call this argument with regular function?

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

With Regular Function

    class UI {
      constructor() {
        this.divRepo = document.querySelector("#repos");
        
      }
    
      showUserRepositories(repos) {
        repos.forEach(function (repo) {

       console.log(this) //output : undefined

          this.divRepo.innerHTML = `
            <div class="mb-2 card-body">
                            <div class="row">
                                <div class="col-md-2">
                                <a href="${repo.html_url}" target = "_blank" id = "repoName" >${repo.name}</a>
                                </div>
                        </div>
        
                        </div>
            `;
        });
      }
    
      
    }

With Arrow Function

class UI {
constructor() {
  this.divRepo = document.querySelector("#repos");
  
}

showUserRepositories(repos) {
  repos.forEach( (repo) => {
    console.log(this) // output : UI {divRepo: div#repos}
    this.divRepo.innerHTML = `
      <div class="mb-2 card-body">
                      <div class="row">
                          <div class="col-md-2">
                          <a href="${repo.html_url}" target = "_blank" id = "repoName" >${repo.name}</a>
                          </div>
                  </div>
  
                  </div>
      `;
  });
}

}

不清楚为什么您不能使用箭头函数,因为箭头函数旨在解决此类问题。如果出于某种原因必须使用非箭头函数,一种选择是使用 second 参数 forEach 来建立 this 上下文:

repos.forEach(function (repo) {
  // ...
}, this);

还有其他选择,例如在闭包中捕获对 this 的引用:

const that = this;
repos.forEach(function (repo) {
  // ...
  console.log(that);
});

...或绑定:

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