[英]Correct way to execute a function when I have function name
I have a string "Car.run(true)"
or "Car.find('window')"
, I want to execute the function run
or find
and also pass respective parameters passed.我有一个字符串
"Car.run(true)"
或"Car.find('window')"
,我想执行 function run
或find
并传递相应的参数。 What is the correct way to do it without using eval
?不使用
eval
的正确方法是什么?
I tried to split the string, extracted the function name and parameters using regex but issue is with boolean values(it will a string after extraction).我尝试拆分字符串,使用正则表达式提取 function 名称和参数,但问题在于 boolean 值(提取后它将是一个字符串)。
Can anyone guide me to resolve this blocker?谁能指导我解决这个阻止程序?
In javascript land, classes are just objects that can be referenced using dictionary lookup syntax在 javascript 领域,类只是可以使用字典查找语法引用的对象
class Car { run(x) { return x } find(x) { return x } }
car = new Car()
method_name = 'run'
car[method_name] # == ƒ run(x) { return x }
car[method_name](1) # == 1
In python land you would need hasattr()
and getattr()
在 python 土地上,您需要
hasattr()
和getattr()
You can try simply like below, if you dont want to use eval
:如果您不想使用
eval
,您可以像下面这样简单地尝试:
var functionHolder = "Car.run(true)";
var myTmpFunction = new Function(functionHolder);
myTmpFunction (); //This would invoke
Generally using eval
is not a good idea, and this isn't great either but it's a start:通常使用
eval
不是一个好主意,这也不是很好,但这是一个开始:
function Car() { this.run = function(args) { console.log('Running', args) } } const str = "Car.run(true)"; // Get the constructor name and the function with arguments as a string const [ctor, fn] = str.split('.'); // The name of the function without parens const fnName = fn.replace(/\((.+)\)/, '') // Get the argument list of the function const originalArgs = fn.match(/\((.+)\)/) // Clean arguments const args = originalArgs[1].split(',').map(str => str.trim()).filter(Boolean); // Instantiate a new object based on the name const f = new(Function.prototype.bind.apply(window[ctor]))(); // Invoke the function with the arguments f[fnName].apply(f, args) // Running true
General idea comes from the AngularJS source and how it instantiates objects from strings.总体思路来自AngularJS 源以及它如何从字符串实例化对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.