silentmatt / expr-eval

Mathematical expression evaluator in JavaScript
http://silentmatt.com/javascript-expression-evaluator/
MIT License
1.18k stars 239 forks source link

How to access parser's parent in a custon function? #242

Closed bscbrn closed 3 years ago

bscbrn commented 3 years ago

I have defined a new custom function and registered into the parser. In the custom function I need to access some data defined in the parent object of the parser but the function gets called without any this object but only the arguments that are set in the expression. Is there any way to access other parser's information from the custom function body?

Thank you for any help

silentmatt commented 3 years ago

You would need to capture a reference to the parser in the function's scope. As long as the parser is visible where you define the function, it should "just work", i.e.:

var parser = new Parser();
// ...
parser.functions.myFunction = function () {
    // parser is visible here because it's in scope where the function was defined
};

If the function is defined somewhere else (in another module for example), you might need to wrap it to bring the parser into scope either as this or a parameter. Something like one of the examples below:

parser.functions.myFunction = function (...args) {
    return myFunction.apply(parser, args);
};

or

parser.functions.myFunction = function (...args) {
    return myFunction(parser, ...args);
};

Hopefully that helps.

bscbrn commented 3 years ago

Thank you very much. As you suggested I accessed the parser var and it simply worked.

silentmatt commented 3 years ago

Great, glad it helped!