【发布时间】:2022-08-10 02:38:56
【问题描述】:
我有这样的代码,在两个不同的文件中有两个不同的类。我想以递归方式调用另一个类函数。我可以在 JavaScript 中实现这一点吗?
// lexer/index.js
const Quote = require(./tokenizer/quote.js)
module.exports = class Lexer {
constructor(args) {
// some get set method callings
}
run () {
return Quote.tokenize(args)
}
}
// lexer/tokenizer/quote
const Lexer = require(\'../index\')
module.exports = class Quote {
// no constructor
// but there could be
static tokenize(args) {
// some calculation for body
// again call the lexer run
const quoteLexer = new Lexer(body)
return quoteLexer.run()
}
}
// index
const Lexer = require(\"./lexer\")
const l = new Lexer(someContent)
console.log(l.run())
目前,我在执行此操作时遇到以下错误。
> node index.js
/home/kiran/dev/markdown-parser/lib/lexer/tokenizer/quote.js:57
const quoteLexer = new Lexer(body)
^
TypeError: Lexer is not a constructor
at Function.tokenize (/home/kiran/dev/markdown-parser/lib/lexer/tokenizer/quote.js:57:24)
代码可以在https://github.com/kiranparajuli589/markdown-parser/pull/17; 找到要复制:只需执行npm install && npm run convert
-
我建议定义类,然后执行
module.exports = ClassName;而不是尝试内联类定义。请参阅How to properly export an ES6 class in Node 4? 及其 cmets 的答案。 -
即使我使用建议的导出模式,同样的错误仍然存在。 :(
-
公平地说,您没有在
Lexer类上定义constructor...也许尝试将constructor() {}添加到Lexer?它不应该是必需的,但我不使用 CommonJS 模块...... -
我在实际代码中有构造函数。只是不在问题中。我也会很快将其添加到问题中。
-
这个问题有帮助吗? stackoverflow.com/questions/10107198
标签: javascript recursion