javascript - 在类的另一个方法中将方法作为参数传递时出错
class Parser {
private tokens: Array<ITokenized>
private token_index: number;
private current_token: ITokenized | undefined;
constructor(tokens: Array<ITokenized>) {
// console.log(tokens);
this.tokens = tokens
this.token_index = -1;
this.current_token = undefined
this.next()
}
next() {
this.token_index += 1;
if (this.token_index < this.tokens.length) {
this.current_token = this.tokens[this.token_index]
}
return this.current_token
}
public parse(): any {
let result = this.expression();
return result;
}
private factor() {
let token = this.current_token
if ([TOK_INT, TOK_FLOAT].includes(token?.dataType)) {
this.next();
return new NumberNode(token?.value).represent();
}
}
private term() {
return this.binaryOperation(this.factor, [TOK_MULTI, TOK_DIVI])
}
private expression() {
return this.binaryOperation(this.term, [TOK_PLUS, TOK_MINUS])
}
public binaryOperation(func: Function, operator: Array<string>) {
let leftNode, operationToken, rightNode;
leftNode = func()
while (operator.includes(this.current_token?.dataType)) {
operationToken = this.current_token;
this.next();
rightNode = func()
leftNode = new BinaryOperator(leftNode, operationToken?.dataType, rightNode).represent();
}
return leftNode;
}
}
export default Parser;F:\Programming-Files\hello-world\dev-projects\puCpp-programming-language\src\parser\Parser.ts:69 return this.binaryOperation(this.factor, [TOK_MULTI, TOK_DIVI]) ^TypeError: 无法读取未定义的属性 'binaryOperation' 在 Parser.term (F:\Programming-Files\hello-world\dev-projects\puCpp-programming-language\src\parser\Parser.ts:69:15) 在 Parser.binaryOperation (F:\Programming-Files\hello-world\dev-projects\puCpp-programming-language\src\parser\Parser.ts:78:14) 在 Parser.expression (F:\Programming-Files\hello-world\dev-projects\puCpp-programming-language\src\parser\Parser. ts:73:15) 在 Parser.parse (F:\Programming-Files\hello-world\dev-projects\puCpp-programming-language\src\parser\Parser.ts:56:21) 在 Runner.start (F:\Programming-Files\hello-world\dev-projects\puCpp-programming-language\src\lexer\Runner.ts:21:26) 在 F:\Programming-Files\hello-world\dev-projects\puCpp-programming-language\src\index.ts:25:46 在 Interface._onLine (readline.js:306:5) 在 Interface._line (readline.js:656:8) 在 Interface._ttyWrite (readline.js:937:14) 在 Socket.onkeypress (readline.js:184:10)
答案#1
尝试显式绑定你的函数参数:
private term() {
return this.binaryOperation(this.factor.bind(this), [TOK_MULTI, TOK_DIVI])
}
private expression() {
return this.binaryOperation(this.term.bind(this), [TOK_PLUS, TOK_MINUS])
}
