![](/img/trans.png)
[英]Execute a JavaScript function when I have its name as a string - Not working
[英]Correct way to execute a function when I have function name
我有一个字符串"Car.run(true)"
或"Car.find('window')"
,我想执行 function run
或find
并传递相应的参数。 不使用eval
的正确方法是什么?
我尝试拆分字符串,使用正则表达式提取 function 名称和参数,但问题在于 boolean 值(提取后它将是一个字符串)。
谁能指导我解决这个阻止程序?
在 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
在 python 土地上,您需要hasattr()
和getattr()
如果您不想使用eval
,您可以像下面这样简单地尝试:
var functionHolder = "Car.run(true)";
var myTmpFunction = new Function(functionHolder);
myTmpFunction (); //This would invoke
通常使用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
总体思路来自AngularJS 源以及它如何从字符串实例化对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.