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

JavaScript模块导出对象调用this.test报'不是函数'错误求解决方案

问题根因

  • 第一版代码报错是this指向丢失导致的:只有直接通过导出对象.iffer()调用时,函数内部的this才会指向导出的对象本身。如果你是将iffer解构后单独调用、或者作为回调函数传递,this会丢失,严格模式下this为undefined,自然找不到test方法。
  • 第二版修改方案无效是因为模块顶层的this在你定义let that = this时还未指向最终的导出对象,ES模块下顶层this本身就是undefined,根本无法访问到导出对象上的test方法。

可行解决方案

方案1:内部直接引用导出对象,不依赖this(最稳妥)

const utils = {
    test() {
        console.log('test')
    },
    iffer(nb) {
        if (nb !== 0) {
            utils.test()
        }
    }
}
module.exports = utils

该方案不受调用方式影响,不管是直接调用还是解构调用iffer都能正常执行。

方案2:手动绑定方法的this指向

const utils = {
    test() {
        console.log('test')
    },
    iffer(nb) {
        if (nb !== 0) {
            this.test()
        }
    }
}
// 把iffer的this永久绑定到utils对象上
utils.iffer = utils.iffer.bind(utils)
module.exports = utils

方案3:调整调用姿势,不修改模块代码

如果不想改动模块内部的代码,只需要保证调用iffer时是挂载在导出对象上调用即可:

// 错误的调用方式(会丢失this)
const { iffer } = require('./你的模块路径')
iffer(1)

// 正确的调用方式
const utils = require('./你的模块路径')
utils.iffer(1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 06:24:03