2017-01-12 33 views
0

它是没关系做到以下几点:从字符串中调用函数的正确方法是什么?

// 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); 

控制台日志:

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

看来工作得很好,但想知道这是否是去这在所有的正确方法?有没有更好的方法或无法预料的影响?

谢谢

+0

貌似[JSONP](http://stackoverflow.com/questions/2067472/what -is-jsonp-all-about) – Andreas

+0

你也可以使用eval调用函数:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval –

回答

1

使用eval方法。

<!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>

+0

为什么你还有c allback()函数呢?如果使用eval()不需要,对吧? –

+0

如果您打算仅调用myFunc,则不需要callBack – Nitheesh

+0

请注意,使用eval()或使用任何其他方式从字符串执行代码是一个严重的安全问题。当字符串来自不可信源时,攻击者可以在网页上下文中执行任何操作。你不应该那样做。 – NineBerry

1

至于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 
相关问题