0

I was making a parser and I got this error.
TypeError: undefined is not an object (evaluating 'this.binop')
This error makes no sense to me I searched StackOverflow a lot and found nothing. Parser:

class Parser {
  tokens: Token[];
  ct: Token;
  tok_idx: number;
  constructor(tokens: Token[]) {
    this.tokens = tokens;
    this.ct = null;
    this.tok_idx = -1;
    this.advance();
  }
  advance(): Token {
    this.tok_idx++;
    if (this.tok_idx < this.tokens.length) {
      this.ct = this.tokens[this.tok_idx];
    }
    return this.ct;
  }

  factor(): NumberNode {
    var token: Token = this.ct;
    if ((Tokens.Int, Tokens.Float).includes(token.type)) {
      this.advance();
      return new NumberNode(token);
    }
  }
  binop(func:Function, tokens: Tokens[]): BinOpNode | NumberNode {
    var left: NumberNode | BinOpNode = func();

    while (tokens.includes(this.ct.type)) {
      var operator: Token = this.ct;
      this.advance();
      var right: NumberNode = func();
      left = new BinOpNode(left, operator, right);
    }
    return left;
  }
  term() {
    return this.binop(this.factor, [Tokens.Mul, Tokens.Div]);
  }
  expr() {
    return this.binop(this.term, [Tokens.Plus, Tokens.Min]);
  }
  parse():BinOpNode|NumberNode{
    var res:BinOpNode|NumberNode = this.expr();
    return res;
  }
}

All of the imports are right and I couldn't figure out what is wrong. Thanks for help

All Code is on GitHub: https://github.com/petranol/PePCscript/ Branch: main

  • `this.binop(this.term, [Tokens.Plus, Tokens.Min])` -> `this.binop(() => this.term(), [Tokens.Plus, Tokens.Min])` and you probably need to make the same transformation in the code inside `term`. – VLAZ Aug 31 '22 at 17:27
  • @VLAZ I don't understand Your Code. Please explain And i [How to access the correct this inside a callback](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) doesn't answer my question –  Aug 31 '22 at 17:30
  • 1
    If you pass `this.term` as parameter, then when executed as a callback, it will lose the value of `this` inside. You need to pass `() => this.term()` instead which will preserve it. – VLAZ Aug 31 '22 at 17:41

0 Answers0