0

I have code like this with two different classes in two different files. I want to call a class function from another just like in a recursive manner. Can I achieve this in 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())

currently, I'm getting the following error while executing this.

> 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)

Code can be found at https://github.com/kiranparajuli589/markdown-parser/pull/17; To reproduce: just do npm install && npm run convert

8
  • I would suggest defining the class, then doing module.exports = ClassName; rather than trying to inline the class definition. See the answers to How to properly export an ES6 class in Node 4? and their comments. Commented Jul 24, 2022 at 13:47
  • the same error persists even if I use the suggested export pattern. :( Commented Jul 24, 2022 at 13:55
  • 1
    To be fair, you don't have a constructor defined on the Lexer class... Maybe try adding constructor() {} to Lexer? It shouldn't be required, but I don't use CommonJS modules... Commented Jul 24, 2022 at 13:58
  • I have the constructor in the actual code. Just not in the question. I'll quickly add it in the question too. Commented Jul 24, 2022 at 13:59
  • Does this question help? stackoverflow.com/questions/10107198 Commented Jul 24, 2022 at 14:00

1 Answer 1

0

Using a code like this solved the problem.

// lexer/index.js
import Quote from "./tokenizer/quote.js"

export default class Lexer{
  run() {
    Quote.tokenize(args)
  }
}
// lexer/tokenizer/quote.js
import Lexer from "../index.js"

export default class Quote {
  static tokenize() {
    const l = new Lexer(args)
    console.log(l.run())
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.