簡體   English   中英

當我有 function 名稱時執行 function 的正確方法

[英]Correct way to execute a function when I have function name

我有一個字符串"Car.run(true)""Car.find('window')" ,我想執行 function runfind並傳遞相應的參數。 不使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM