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

JS普通脚本转类实现多实例时读取存在的属性报错如何解决?

问题原因

报错的核心是this指向丢失:
你通过window.requestAnimationFrame(this.isInViewport)传递方法作为回调时,方法的执行上下文会和实例解绑。回调触发时this不再指向Marquee类的实例,严格模式下会变成undefined,所以读取this.marquee就会抛出错误。
第一次调用isInViewport是通过实例的init()方法触发的,this指向正常,所以你能通过console.log打印出属性值,第二次及之后都是requestAnimationFrame触发回调,此时this已经丢失,就触发了报错。

解决方案

任选一种即可:

方案1:将方法改为箭头函数

箭头函数会继承定义时的this指向,不会被调用方式影响,修改isInViewport的定义:

isInViewport = () => {
  // 原有逻辑不变
  if (this.marquee) {
    // ... 原有代码
    window.requestAnimationFrame(this.isInViewport);
  }
}

方案2:回调时绑定this

调用requestAnimationFrame时手动绑定当前实例的this:

// 把原有最后一行调用改成
window.requestAnimationFrame(this.isInViewport.bind(this));

方案3:构造函数中提前绑定

在类的constructor中提前绑定方法的this指向:

constructor(el) {
  this.marquee = el;
  this.maxSpeed = 20;
  this.lerpScroll = 0;
  this.lastScrollPos = 0;
  // 新增绑定
  this.isInViewport = this.isInViewport.bind(this);
}

额外注意

你当前代码里还有一个隐形问题:container.style.transform = getDirection;是无效赋值,transform属性需要指定变换函数和单位,比如要实现横向倾斜可以改成:

container.style.transform = `skewX(${getDirection * 0.1}deg)`;

你可以根据实际需求调整变换类型和系数。

内容的提问来源于stack exchange,提问作者Toni Michel Caubet

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 17:36:03