同一.js文件内调用已导出函数失败,如何排查解决?
解决同一模块内导出函数互相调用的问题
你遇到的问题是因为在STRONG_UPTREND函数内部,直接引用SMA时当前作用域不存在该变量——你仅将SMA挂载到exports对象,未在模块顶层作用域暴露这个函数名;而this.SMA无效,是因为当函数被作为独立导出项调用时(比如外部代码解构使用const { STRONG_UPTREND } = require('./your-module')),函数内部的this并不会指向exports对象。
下面是几种可行的解决方案:
方案1:先定义函数,再统一导出
先在模块顶层定义所有函数,让函数之间可以直接通过函数名互相调用,最后再将需要导出的函数挂载到exports上:
// 先定义函数,模块内可直接调用 async function SMA(ohlcv, period) { const close = ohlcv.map((c) => c[OHLCV_INDEX.CLOSE]); const result = await tulind.indicators.sma.indicator([close], [period]); const sma = result[0][result[0].length - 1]; return sma; }; async function STRONG_UPTREND(ohlcv, period1, period2, period3) { const close = ohlcv.map((c) => c[OHLCV_INDEX.CLOSE]); // 直接调用顶层定义的SMA函数 const sma1 = await SMA(ohlcv, period1); const sma2 = await SMA(ohlcv, period2); const sma3 = await SMA(ohlcv, period3); const last_close = close[close.length - 1]; if (last_close >= sma1 && last_close > sma2 && last_close > sma3) return true; return false; }; // 统一导出需要暴露的函数 exports.SMA = SMA; exports.STRONG_UPTREND = STRONG_UPTREND;
方案2:在函数内部通过exports引用
如果不想调整函数定义顺序,可以直接在STRONG_UPTREND里使用exports.SMA来调用:
exports.SMA = async function (ohlcv, period) { const close = ohlcv.map((c) => c[OHLCV_INDEX.CLOSE]); const result = await tulind.indicators.sma.indicator([close], [period]); const sma = result[0][result[0].length - 1]; return sma; }; exports.STRONG_UPTREND = async function (ohlcv, period1, period2, period3) { const close = ohlcv.map((c) => c[OHLCV_INDEX.CLOSE]); // 通过exports直接调用已导出的SMA函数 const sma1 = await exports.SMA(ohlcv, period1); const sma2 = await exports.SMA(ohlcv, period2); const sma3 = await exports.SMA(ohlcv, period3); const last_close = close[close.length - 1]; if (last_close >= sma1 && last_close > sma2 && last_close > sma3) return true; return false; };
方案3:使用模块内的对象统一管理函数
把所有函数放在一个对象里,内部通过对象属性调用,最后导出这个对象:
const indicators = { async SMA(ohlcv, period) { const close = ohlcv.map((c) => c[OHLCV_INDEX.CLOSE]); const result = await tulind.indicators.sma.indicator([close], [period]); const sma = result[0][result[0].length - 1]; return sma; }, async STRONG_UPTREND(ohlcv, period1, period2, period3) { const close = ohlcv.map((c) => c[OHLCV_INDEX.CLOSE]); // 通过对象属性调用SMA const sma1 = await this.SMA(ohlcv, period1); const sma2 = await this.SMA(ohlcv, period2); const sma3 = await this.SMA(ohlcv, period3); const last_close = close[close.length - 1]; if (last_close >= sma1 && last_close > sma2 && last_close > sma3) return true; return false; } }; module.exports = indicators;
注意这种方式下,外部调用时需要通过对象访问(比如const indicators = require('./your-module'); indicators.STRONG_UPTREND(...)),如果解构调用,this会丢失指向,需要用bind或者箭头函数修正。
内容的提问来源于stack exchange,提问作者BitQueen
相关产品推荐
相关产品推荐

