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

在TypeScript中如何调整this指针使其指向新建的Image实例

TypeScript 中让 Image 实例 onload 回调的 this 指向实例的解决方案

出现该问题的核心原因通常是使用了箭头函数作为 onload 回调,箭头函数的 this 会在定义时继承外层作用域的指向,无法在运行时被修改为指向 Image 实例。可以通过以下几种方式实现需求:

  • 方案1:使用普通函数作为回调,TS 中显式标注 this 类型
    浏览器触发 DOM 元素的事件回调时,默认会将回调的 this 指向触发事件的元素本身,只要不使用箭头函数即可生效,只需要给 TS 补充 this 参数的类型标注(该参数为 TS 语法糖,不会影响实际运行参数):
const myImage = new Image();
myImage.onload = function(this: HTMLImageElement) {
  // 此处 this 直接指向当前 new 出来的 Image 实例
  console.log('图片宽度', this.width);
  console.log('图片地址', this.src);
};
myImage.src = '你的图片地址';
  • 方案2:直接通过变量引用访问 Image 实例
    如果需要同时用到外层作用域的 this,可以不依赖回调内部的 this,直接通过提前定义的 Image 实例变量访问:
// 外层作用域的 this 可正常使用
const myImage = new Image();
myImage.onload = () => {
  // 直接访问 myImage 变量即可拿到实例,同时可正常访问外层 this
  console.log('图片宽度', myImage.width);
};
myImage.src = '你的图片地址';
  • 方案3:使用 addEventListener 绑定加载事件
    和 onload 赋值逻辑一致,使用普通函数作为回调即可:
const myImage = new Image();
myImage.addEventListener('load', function(this: HTMLImageElement) {
  console.log('图片加载完成', this.naturalWidth);
});
myImage.src = '你的图片地址';

代码运行截图

内容的提问来源于stack exchange,提问作者shunze.chen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 05:06:03