Home > other >  (Angular, TypeScript) Create new function from string that has if condition (without eval())
(Angular, TypeScript) Create new function from string that has if condition (without eval())

Time:08-27

How can I create a new function from a string when the string contains if condition? The string will comes from outside but in the dummy example below everything is hardcoded to be easier.

let f1: number = 1;
let f2: number = 0;
let condition: string = 'if(this.f1===1){this.f2 = 1}';

let result = this.createFn(condition);

createFn(param: string) {
  return new Function('return '   param)();
  // or return new Function(param)();
}

Of course this is not working and I'm searching a way to do it. I don't want to use eval().

CodePudding user response:

Passing a string to the constructor of Function is almost the same as using eval().

To safely execute arbitrary code in JavaScript you need to have a JavaScript interpreter written in JavaScript which will then execute the received string in a sandbox environment. A quick google search yields this package: https://github.com/NeilFraser/JS-Interpreter.

Others who faced this issue have decided to implement themselves a domain-specific subset of a programming language to then allow the strings to execute that language's code. e.g. SAP's SAPUI5/OpenUI5 solution for the Expression Binding they have.

CodePudding user response:

The constructor for a Function doesn't create closure, that is, it won't access local variables, but global ones.

If you have

var f1 = 1;
var f2 = 2;
let condition = 'if(this.f1===1){this.f2=1}';
new Function(condition)();
console.log(f2);

You'll see that f2 equals 1. But if you use 'let' instead of 'var', the function won't have access to the variable and f2 will equal 2.

  • Related