You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将this传递给window.onscroll事件绑定的函数以解决调用报错?

解决onscroll回调中this指向错误的问题

这个问题我太熟啦!你遇到的是JavaScript里经典的this指向陷阱——当你直接把函数赋值给window.onscroll时,回调函数内部的this默认会指向window对象,而不是你的类实例,所以才会报错“this.currentItemCount()不是函数”。下面给你几种靠谱的解决方法:

方法1:用箭头函数(最简单直接)

箭头函数不会绑定自己的this,它会继承外层作用域的this(也就是你的类实例),直接替换成箭头函数就行:

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

方法2:提前保存this的引用(兼容旧浏览器)

如果你的项目需要支持IE这类不支持箭头函数的旧浏览器,可以先把当前实例的this存到一个变量里(比如that或者self),然后在回调里用这个变量:

init() {
  const that = this; // 把类实例的this存起来
  window.onscroll = function() {
    if(that.currentItemCount() > that.totalElements){
      that.totalElements = that.currentItemCount();
      that.myFunction();
    }
  };
}

方法3:用bind()绑定this

bind()方法会返回一个新函数,把函数内部的this固定成你传入的对象,这里就是你的类实例:

init() {
  window.onscroll = function() {
    if(this.currentItemCount() > this.totalElements){
      this.totalElements = this.currentItemCount();
      this.myFunction();
    }
  }.bind(this); // 绑定类实例的this到回调函数
}

额外建议:用addEventListener绑定事件(更规范)

直接赋值给window.onscroll会覆盖之前的滚动事件监听,推荐用addEventListener来添加监听,这样可以同时存在多个滚动回调:

init() {
  // 用箭头函数继承this
  window.addEventListener('scroll', () => {
    if(this.currentItemCount() > this.totalElements){
      this.totalElements = this.currentItemCount();
      this.myFunction();
    }
  });
  
  // 或者用bind的方式,方便后续移除监听
  // const scrollHandler = function() { ... }.bind(this);
  // window.addEventListener('scroll', scrollHandler);
  // 销毁时:window.removeEventListener('scroll', scrollHandler);
}

最后再确认一下:currentItemCount()和myFunction()一定要是你的类的实例方法(不是静态方法),不然即使解决了this指向问题,还是会找不到函数哦~

内容的提问来源于stack exchange,提问作者Francesca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:23:24