0

我写了以下代码(模拟):

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

我收到错误“测试不是函数”。

并尝试了以下方法:

let that = this
module.exports = {
    test() {
        console.log('test')
    },
    iffer(nb) {
        if (nb !== 0) {
            that.test()
        }
    }
}

该解决方案仍然无法正常工作,因为 JavaScript 模块默认开启了严格模式。有谁知道这个问题的解决方案?

4

1 回答 1

2

只是module.exports再次参考。

iffer(nb){
    if (nb !== 0) {
        module.exports.test()
    }
}

您也可以先将导出的对象放入独立变量中,以使其更易于引用。或者,让所有函数都是独立的以便于参考,然后导出一个包含所有函数的对象。

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

如果您的环境与 ES6 模块语法兼容,我建议您改用它们。

export const test = () => console.log('test');
export const iffer = (nb) => {
    if (nb !== 0) {
        test();
    }
};
于 2021-11-06T23:39:25.100 回答