0

I came across two javascript functions, f1 and f2:

const expression = "model.test ==0";
const x = ["model"].concat(`return ${expression};`);
const f1 = Function.apply(Function, x);
const f2 = Function.bind.apply(Function,x)();

I figure out f1({ test: 1 }), it will return false while f1({ test: 0 }) will return true.

I don't know how to call f2 at all. The two keywords Function inside each function definition confuses me completely.

Can someone explain what is happening here?

The original function is ad following

export function evalStringExpression(expression: string, argNames: string[]) 
{
  try {
    return Function.bind.apply(Function, [void 
      0].concat(argNames.concat(`return ${expression};`)))();
   } catch (error) {
  console.error(error);
  }
}

// to call :

hideExpression = evalStringExpression(hideExpression, ['model', 'formState']);
        }

f_hideExpression = (model, formState) =>  hideExpression(model, formState);

I don't know f_hideExpression is value or function or object.

The code is from https://github.com/formly-js/ngx-formly/search?q=evalStringExpression&unscoped_q=evalStringExpression

it creates a function based on expression input. It works pretty magically, I am trying to figurate out how.

3

1 Answer 1

1

f2 makes no sense whatsoever.

const f2 = Function.bind.apply(Function,x)();

is

const f2 = Function.bind(...x)();

is

const f2 = Function.call(...x);

is

const f2 = Function.call("model", 'return "model.test ==0";');

but Function ignores its this value so this is the same as

const f2 = Function('return "model.test ==0";');

which has no parameters and creates a closure over the global model variable.

Sign up to request clarification or add additional context in comments.

1 Comment

I think the const f2 = Function('model', 'return "model.test ==0";')(); it allows to call f2(model) instead of limited to global model. Thanks!

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.