简体   繁体   中英

Assigning a specific function CALL to a variable

I am trying to run a function call with parameters stored all as a function.

I have simplified my code to show what i am trying to do, but its just the same with some changes for less confusion.

 function addNums(x,y) { var z = x + y; console.log(z); } var runFunction = 'addNums(12,6)' runFunction;

Hopefully ive made it clear what i am trying to do here, I am not getting an error from the last line, it just doesnt run!

Thanks.

function addNums(x, y) {
  const z = x + y;
  console.log(z);
}

const runFunction = () => addNums(12, 6);

runFunction();

This should work for you. As someone else mentioned you can use eval but you should generally avoid that since it can be dangerous.

You can use eval to execute the code contained in a string:

 function addNums(x,y) { var z = x + y; console.log(z); } var runFunction = 'addNums(12,6)' eval(runFunction); // Here!

You can also bind the call if you don't want to immediately invoke the function.

 function addNums(x,y) { var z = x + y; console.log(z); } var runFunction = addNums.bind(this,12,6); runFunction();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM