传递给window.onscroll函数 [英] Passing this to window.onscroll function

查看:192
本文介绍了传递给window.onscroll函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I pass this to a function assigned to my window.onscroll event?

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

I am trying to trigger myFunction() when a certain condition is met. I need to check this condition onscroll

  init() {
    window.onscroll = function() {
      if(this.currentItemCount() > this.totalElements){
        this.totalElements = this.currentItemCount();
        this.myFunction();
      }
    };
  }

但是我得到一个错误,该错误是 this.currentItemCount( )不是函数。我知道我需要将 this 传递给 window.onscroll ,但是我找不到正确的语法。

However I get an error that this.currentItemCount() is not a function. I know that I need to pass this to window.onscroll but I cannot figure out the correct syntax.

推荐答案

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

You can use that = this construct. (What does 'var that = this;' mean in JavaScript?)

init() {
    var that = this;
    window.onscroll = function() {
      if(that.currentItemCount() > that.totalElements){
        that.totalElements = that.currentItemCount();
        that.myFunction();
      }
    };
  }

甚至更好地使用箭头功能保留<包装环境中的code> this (需要ES6支持或编译器):

Or even better use arrow function which preserves this from the wrapping context (ES6 support or transpiler required):

init() {
    window.onscroll = () => {
      if(this.currentItemCount() > this.totalElements){
        this.totalElements = this.currentItemCount();
        this.myFunction();
      }
    };
  }

这篇关于传递给window.onscroll函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆