Skip to content Skip to sidebar Skip to footer

Passing This To Window.onscroll Function

How can I pass this to a function assigned to my window.onscroll event? I am trying to trigger myFunction() when a certain condition is met. I need to check this condition onscroll

Solution 1:

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();
      }
    };
  }

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();
      }
    };
  }

Solution 2:

You can try this:

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

this isn't available from the inner scope, but self will be available.

Post a Comment for "Passing This To Window.onscroll Function"