简体   繁体   English

从字符串调用函数的正确方法是什么?

[英]What is the correct way to call a function from a string?

Is it okay to do the following: 可以执行以下操作吗?

// Response from an API as a string, that contains a function to call.
const stringFunc = 'myFunc({"Status":200,"Message":"This is a message"})';

function myFunc(obj) {
  console.log(obj);
}

function callBack(stringFn) {
  return Function.prototype.call(stringFn);
}

callBack(stringFunc);

Console logs: 控制台日志:

{"Status":200,"Message":"This is a message"}

It seems to work just fine, but wanted to know if this was the correct way to go about this at all? 似乎工作正常,但想知道这是否是解决此问题的正确方法? Are there any better methods or unforeseen implications? 有更好的方法或无法预料的影响吗?

Thanks 谢谢

Use eval method. 使用评估方法。

 <!DOCTYPE html> <html> <body> <script> const stringFunc = 'myFunc({"Status":200,"Message":"This is a message"})'; function myFunc(obj) { console.log(obj); } function callBack(stringFn) { return Function.prototype.call(stringFn); } eval(stringFunc); </script> </body> </html> 

As an alternative to eval you can use the Function constructor: 作为eval的替代方法,您可以使用Function构造函数:

const stringFunc = 'myFunc({"Status":200,"Message":"This is a message"})';

function myFunc(obj) {
  console.log(obj);
}

const payloadFunc = new Function(stringFunc);
payloadFunc() //logs the object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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