Passing this to [removed] function

2019-08-27 05:35发布

问题:

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

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

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.

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


回答2:

You can try this:

init() {
    var self = 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.