将其传递给 window.onscroll 函数

Fra*_*sca 0 javascript this ecmascript-6

如何传递this给分配给我的事件的函数window.onscroll

我试图myFunction()在满足特定条件时触发。我需要检查这个情况onscroll

  init() {
    window.onscroll = function() {
      if(this.currentItemCount() > this.totalElements){
        this.totalElements = this.currentItemCount();
        this.myFunction();
      }
    };
  }
Run Code Online (Sandbox Code Playgroud)

this.currentItemCount()但是我收到一个不是函数的错误。我知道我需要传递thiswindow.onscroll但我无法弄清楚正确的语法。

cro*_*raf 5

您可以使用that = this构造。(“var that = this;”在 JavaScript 中是什么意思?

init() {
    var that = this;
    window.onscroll = function() {
      if(that.currentItemCount() > that.totalElements){
        that.totalElements = that.currentItemCount();
        that.myFunction();
      }
    };
  }
Run Code Online (Sandbox Code Playgroud)

或者甚至更好地使用箭头函数来保留this包装上下文(需要 ES6 支持或转译器):

init() {
    window.onscroll = () => {
      if(this.currentItemCount() > this.totalElements){
        this.totalElements = this.currentItemCount();
        this.myFunction();
      }
    };
  }
Run Code Online (Sandbox Code Playgroud)